html5屬性placeholder的js 向下相容支援(jquery版)

來源:互聯網
上載者:User

標籤:style   blog   io   ar   color   os   sp   for   on   

placeholder是html5表單特性中比較好用的一條,但是苦於其向下相容性,所以一般要做向下相容的網站都不敢用,如果有用到的地方,也是用js簡單類比而實現的,那麼有沒有一個一勞永逸的方法去解決這個問題呢?

接下來我就來帶大家實現這個方案:

if (‘placeholder‘ in document.createElement(‘input‘)) return;

這句代碼的意思是判斷是否是支援placeholder屬性的,如果支援則return,不執行下面代碼。

if (this.type == ‘submit‘ || this.type == ‘button‘ || this.type == ‘reset‘) return;

當然,如果input的type是一個按鈕,也不需要placeholder。

接下來,就開始實現了

$.fn.placeholderSupport = function(opts){    opts = $.extend({},opts);    return this.each(function(){        //main code    });  }

 

 


 

上述代碼是編寫擴充$.fn外掛程式的基本代碼,後面方法會被放置進jQuery選取器傳回值中,也就是$(選取器)裡面直接調用。

由於$()返回可能是個jQuery對象數組,所以外掛程式裡面一般會進行each,return是標準寫法,讓jQuery能連結起來,如$().function()......

基礎架構就搭好了,開幹!

var _this = $(this);var placeholderText = _this.attr(‘placeholder‘) || ‘‘;if (this.type == ‘text‘ || this.type == ‘email‘) {    this.value = placeholderText;    _this.on(‘focus‘, function() {        if (this.value === placeholderText) this.value = ‘‘;    });    _this.on(‘blur‘, function() {        if (this.value === ‘‘) this.value = placeholderText;    });}

this是each裡面的每個input,先得到placeholder的值,並緩衝起來。

判斷type是‘text‘||‘email‘時候執行下面(html5的input type比較多,這裡先做了這兩個的支援,此處不做email驗證);
上面代碼是解決普通容器的方法,接下來就是最難纏的type=‘password‘的時候。

var id = this.id;if (id === ‘‘) {    this.id = ‘placeholderBuild_‘ + Base.supportId;    id = ‘placeholderBuild_‘ + Base.supportId;}var label = $(‘<label for="‘ + id + ‘">‘ + placeholderText + ‘</label>‘);var css = {    ‘left‘: 5 - $(this).outerWidth(true),    ‘width‘: $(this).outerWidth(true),    ‘height‘: $(this).outerHeight(true),    ‘line-height‘: $(this).outerHeight(true) + ‘px‘,    ‘position‘: ‘absolute‘,    opacity: ‘0.5‘};var valiM = $(‘<span></span>‘).css({    position: ‘relative‘});label.css(css).appendTo(valiM);valiM.insertAfter($(this));$(this).on(‘focus‘, function() {    label.hide();}).on(‘blur‘, function() {    if (this.value === ‘‘) label.show();});

賦值id,Base是全域變數對象。

大致思路是建立一個空的<span>放到input後面,然後在這個空的span裡append個label,並把label 的for id設定成input的id,(for是html5特性,所以此處略矛盾)。

給label賦值寬高,position, left,top,opacity等。

然後繼續綁定focus,blur方法。

就這麼簡單。

 調用的時候,直接在

$(function(){
   $(‘input‘).placeholderSupport();
});

當有非同步dom處input需要支援時候,也只組要找到這個input,然後:
$(input).placeholderSupport();

代碼寫很老了,沒怎麼最佳化過,Base可以用$替換,也可以用自己的全域變數對象搞定。
附上完整原始碼:

placeholderSupport: function() {            if (‘placeholder‘ in document.createElement(‘input‘)) return this;            if (!Base.supportId) {                Base.supportId = 0;            }            return this.each(function(e) {                Base.supportId++;                if (this.type == ‘submit‘ || this.type == ‘button‘ || this.type == ‘reset‘) return;                var placeholderText = $(this).attr(‘placeholder‘) || ‘‘;                if (this.type == ‘text‘ || this.type == ‘email‘) {                    this.value = placeholderText;                    $(this).on(‘focus‘, function() {                        if (this.value === placeholderText) this.value = ‘‘;                    });                    $(this).on(‘blur‘, function() {                        if (this.value === ‘‘) this.value = placeholderText;                    });                } else if (placeholderText !== ‘‘ && this.type === ‘password‘) {                    var id = this.id;                    if (id === ‘‘) {                        this.id = ‘placeholderBuild_‘ + Base.supportId;                        id = ‘placeholderBuild_‘ + Base.supportId;                    }                    var label = $(‘<label for="‘ + id + ‘">‘ + placeholderText + ‘</label>‘);                    var css = {                        ‘left‘: 5 - $(this).outerWidth(true),                        ‘width‘: $(this).outerWidth(true),                        ‘height‘: $(this).outerHeight(true),                        ‘line-height‘: $(this).outerHeight(true) + ‘px‘,                        ‘position‘: ‘absolute‘,                        opacity: ‘0.5‘                    };                    var valiM = $(‘<span></span>‘).css({                        position: ‘relative‘                    });                    label.css(css).appendTo(valiM);                    valiM.insertAfter($(this));                    $(this).on(‘focus‘, function() {                        label.hide();                    }).on(‘blur‘, function() {                        if (this.value === ‘‘) label.show();                    });                }            });        }

 

html5屬性placeholder的js 向下相容支援(jquery版)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.