DIV CSS 佈局教程網

封裝 jQuery placeholder 插件,讓舊版瀏覽器也有提示文字
編輯:JQuery入門技巧     

輸入框裡那層灰色的提示文字,現在只要寫 placeholder 屬性就好:

<input type="text" name="username" placeholder="請輸入用戶名" value="" id="username"/>

想微調顏色,加上幾行 CSS 即可:

input::-webkit-input-placeholder { color: #AAAAAA; }

問題是舊版瀏覽器(尤其是 IE8、IE9)根本不認這個屬性。若專案還必須支援它們,就得自己寫一個模擬版本。以下示範如何封裝成 jQuery 插件。

一、約定呼叫方式

目標是讓使用方式盡量簡單:

$('input').placeholder();

二、插件骨架與能力偵測

;(function($){
  $.fn.placeholder = function(options){
    options = $.extend({
      placeholderColor: '#aaaaaa',
      isSpan: false,  // 是否用插入 span 的方式模擬,預設否
      onInput: true   // 是否即時監聽輸入
    }, options);

    // 用 return this.each 保留鏈式呼叫能力
    return this.each(function(){
      var _this = this;
      var supportPlaceholder = 'placeholder' in document.createElement('input');
      if (!supportPlaceholder){
        // 不支援時才執行模擬
      }
    });
  };
})(jQuery);

'placeholder' in document.createElement('input') 是最經典的特性偵測寫法:支援就什麼都不做,讓原生行為接管。

三、方案 A:用 value 模擬

把提示文字直接塞進 value,聚焦時清空、失焦時若為空則填回,並用顏色區分:

if (!options.isSpan){
  $(_this)
    .focus(function () {
      var pattern = new RegExp("^" + defaultValue + "$|^$");
      pattern.test($(_this).val()) && $(_this).val('').css('color', defaultColor);
    })
    .blur(function () {
      if ($(_this).val() == defaultValue) {
        $(_this).css('color', defaultColor);
      } else if ($(_this).val().length == 0) {
        $(_this).val(defaultValue).css('color', options.placeholderColor);
      }
    })
    .trigger('blur');
}

這種做法的缺點是會污染 value,表單序列化時可能把提示文字一起送出去,所以要在提交前多一道清理。

四、方案 B:用 span 覆蓋模擬

如果不想動 value,就在輸入框前面插一個 span,樣式對齊輸入框,看起來就像提示文字:

var $simulationSpan = $('<span class="wrap-placeholder">' + defaultValue + '</span>');
$simulationSpan.css({
  'position': 'absolute',
  'display': 'inline-block',
  'overflow': 'hidden',
  'width': $(_this).outerWidth(),
  'height': $(_this).outerHeight(),
  'color': options.placeholderColor,
  'margin-left': $(_this).css('margin-left'),
  'margin-top': $(_this).css('margin-top'),
  'padding-left': parseInt($(_this).css('padding-left')) + 2 + 'px',
  'padding-top': _this.nodeName.toLowerCase() == 'textarea'
                  ? parseInt($(_this).css('padding-top')) + 2 : 0,
  'line-height': _this.nodeName.toLowerCase() == 'textarea'
                  ? $(_this).css('line-height') : $(_this).outerHeight() + 'px',
  'font-size': $(_this).css('font-size'),
  'font-family': $(_this).css('font-family'),
  'font-weight': $(_this).css('font-weight')
});

// 插到輸入框前面,點它就把焦點交還給輸入框
$(_this).before($simulationSpan.click(function () {
  $(_this).trigger('focus');
}));

// 已有內容時先隱藏 span
$(_this).val().length != 0 && $simulationSpan.hide();

if (options.onInput) {
  // 綁定 input / propertychange,即時切換顯示
  var inputChangeEvent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange';
  $(_this).bind(inputChangeEvent, function () {
    $simulationSpan[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block';
  });
} else {
  $(_this).focus(function () {
    $simulationSpan.hide();
  }).blur(function () {
    /^$/.test($(_this).val()) && $simulationSpan.show();
  });
}

五、完整插件

;(function($){
  $.fn.placeholder = function(options){
    options = $.extend({
      placeholderColor: '#aaaaaa',
      isSpan: false,
      onInput: true
    }, options);

    return this.each(function(){
      var _this = this;
      var supportPlaceholder = 'placeholder' in document.createElement('input');
      if (supportPlaceholder) return;

      var defaultValue = $(_this).attr('placeholder');
      var defaultColor = $(_this).css('color');

      if (!options.isSpan){
        // 方案 A:以 value 模擬(此處同上一節程式碼)
      } else {
        // 方案 B:以 span 模擬(此處同上一節程式碼)
      }
    });
  };
})(jQuery);

六、使用方式

// 預設(value 模擬)
$("#username").placeholder();

// 改用 span 模擬
$("#username").placeholder({ isSpan: true });

現代的建議:如果專案已經不再需要支援 IE9 以下的瀏覽器,直接用原生 placeholder 就好,不必背這段程式碼。真要相容舊版,也可以考慮成型 polyfill 套件,而自己實作的好處是完全可控、能配合既有設計稿調整細節。

以上就是 jQuery 封裝 placeholder 效果的完整做法,供大家參考。

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