jQuery Mobile 會自動為 HTML 表單自動添加樣式,讓它們看起來更具吸引力,觸摸起來更具友好性。




jQuery Mobile 表單結構

jQuery Mobile 使用 CSS 為 HTML 表單元素添加樣式,讓它們更具吸引力,更易于使用。

在 jQuery Mobile 中,您可以使用下列表單控件:

  • 文本輸入框

  • 搜索輸入框

  • 單選按鈕

  • 復選框

  • 選擇菜單

  • 滑動條

  • 翻轉(zhuǎn)撥動開關

當使用 jQuery Mobile 表單時,您應當知道:

  • <form> 元素必須有一個 method 和一個 action 屬性

  • 每個表單元素必須有一個唯一的 "id" 屬性。id 必須是整個站點所有頁面上唯一的。這是因為 jQuery Mobile 的單頁導航機制使得多個不同頁面在同一時間被呈現(xiàn)

  • 每個表單元素必須有一個標簽。設置標簽的 for 屬性來匹配元素的 id

實例

<form method="post" action="demoform.html">
 <label for="fname">姓名:</label>
 <input type="text" name="fname" id="fname">
</form>

如需隱藏標簽,請使用 class ui-hidden-accessible。這在您把元素的 placeholder 屬性作為標簽時經(jīng)常用到:                  

實例

<form method="post" action="demoform.html">

 <label for="fname" class="ui-hidden-accessible">姓名:</label>
 <input type="text" name="fname" id="fname" placeholder="姓名...">
</form>

提示:  我們可以使用 data-clear-btn="true" 屬性來添加清除輸入框內(nèi)容的按鈕 (一個在輸入框右側(cè)的 X 圖標):

實例

<label for="fname">姓名:</label>
<input type="text" name="fname" id="fname" data-clear-btn="true">


點擊 "運行實例" 按鈕查看在線實例 

Note清除輸入框的按鈕可以在 <input> 元素中使用,但不能在 <textarea> 中使用。 搜索框中 data-clear-btn 默認值為 "true" ,你可以使用 data-clear-btn="false" 移除該圖標。

jQuery Mobile 表單圖標

表單中的按鈕代碼是標準的 HTML <input> 元素 (button, reset, submit)。他們會自動渲染樣式,可以自動適配移動設備與桌面設備:

實例

<input type="button" value="按鈕">
<input type="reset" value="重置按鈕">
<input type="submit" value="提交按鈕">

如果需要在 <input> 按鈕中添加額外的樣式,可以使用下表中的 data-* 屬性:

屬性描述
data-cornerstrue | false指定按鈕是否有圓角
data-icon圖標參考手冊指定按鈕圖標
data-iconposleft | right | top | bottom | notext指定圖標位置
data-inlinetrue | false指定是否內(nèi)聯(lián)按鈕
data-minitrue | false指定是否為迷你按鈕
data-shadowtrue | false指定按鈕是否添加陰影效果

按鈕添加圖標:

實例

<input type="button" value="按鈕">
<input type="reset" value="重置按鈕">
<input type="submit" value="提交按鈕">

字段容器

如需讓標簽和表單元素看起來更適應寬屏,請用帶有 "ui-field-contain" 類的 <div> 或 <fieldset> 元素包圍 label/form 元素:

實例

<form method="post" action="demoform.php">
  <div class="ui-field-contain">
    <label for="fname">姓:</label>
    <input type="text" name="fname" id="fname">
    <label for="lname">姓:</label>
    <input type="text" name="lname" id="lname">
  </div>
</form>

ui-field-contain 類基于頁面的寬度為標簽和表單控件添加樣式。當頁面的寬度大于 480px 時,它會自動把標簽放置在與表單控件同一線上。當頁面的寬度小于 480px 時,標簽會被放置在表單元素的上面。

提示:為了防止 jQuery Mobile 為可點擊元素自動添加樣式,請使用 data-role="none" 屬性:

實例

<label for="fname">姓名:</label>

<input type="text" name="fname" id="fname" data-role="none">


lampjQuery Mobile 中的表單提交

jQuery Mobile 通過 AJAX 自動處理表單提交,并將試圖集成服務器響應到應用程序的 DOM 中。