DIV CSS 佈局教程網

jQuery 輸入框的焦點提示文字效果
編輯:JQuery特效代碼     

在沒有 placeholder 屬性的年代,輸入框裡的提示文字得靠自己寫。這份範例示範了兩種觸發時機。

<script type="text/javascript">
$(function () {
  // 類型一:取得焦點時提示消失,離開時依內容決定是否顯示
  $("#focus .input_txt").each(function () {
    var thisVal = $(this).val();
    if (thisVal != "") {
      $(this).siblings("span").hide();
    } else {
      $(this).siblings("span").show();
    }
    $(this).focus(function () {
      $(this).siblings("span").hide();
    }).blur(function () {
      if ($(this).val() != "") {
        $(this).siblings("span").hide();
      } else {
        $(this).siblings("span").show();
      }
    });
  });

  // 類型二:一旦開始輸入就永久隱藏提示
  $("#keydown .input_txt").each(function () {
    $(this).keyup(function () {
      $(this).siblings("span").hide();
    }).blur(function () {
      if ($(this).val() != "") {
        $(this).siblings("span").hide();
      } else {
        $(this).siblings("span").show();
      }
    });
  });
})
</script>

<style>
label { display: block; position: relative; margin: 20px 0; }
span { position: absolute; left: 10px; line-height: 40px; color: #BCBCBC; cursor: text; }
.input_txt { width: 398px; height: 38px; border: 1px solid #ccc; text-indent: 10px; }
</style>

<form id="focus">
  <label><span>註冊郵箱</span><input type="text" class="input_txt" /></label>
  <label><span>密碼</span><input type="text" class="input_txt" /></label>
</form>

結構上把提示文字做成 label 內的 span,用絕對定位疊在輸入框上方;輸入框本身保持空值,靠 span 顯示提示。好處是提示文字不會被誤送進後端,也不會在使用者輸入時混在值裡。

如今 HTML5 的 <input placeholder="註冊郵箱"> 已 natively 完成這一切,還能自動處理瀏覽器與無障礙支援。這段程式適合成為理解 focus/blur 事件與 siblings 操作的練習,新專案則建議直接用 placeholder,並搭配表單驗證確保必填欄位不被略過。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved