js解決IE8、9下placeholder的相容問題

來源:互聯網
上載者:User

標籤:

由於placeholder是html5的新屬性,在IE8、IE9下是不能顯示的,有相容性問題。

解決思路:

1.判斷目前瀏覽器是否支援placeholder屬性

2.若不支援,則將type="text"的input標籤的value值設定為placeholder的值,類比placeholder效果;若是type="password",則添加一個type="password"的input元素類比。

 

代碼:

 

 

<div>    <input id="account"  style="height: 45px; padding: 6px 25px; line-height: 31px" type="text" class="form-control" placeholder="使用者名稱/手機號" ></div><div id="pwdDiv">    <input id="password"  style="height: 45px; padding:6px 25px; line-height: 31px" type="password" class="form-control" placeholder="密碼"></div>
 (function($){        //判斷瀏覽器是否支援placeholder屬性        var supportPlaceholder = ‘placeholder‘in document.createElement(‘input‘);        //初始化        var placeholder = function(input){            var text = input.attr(‘placeholder‘);            var defaultValue = input.defaultValue;            if(!defaultValue && input.attr(‘type‘) == "text"){                input.val(text);            }        };        //當瀏覽器不支援placeholder屬性時,調用placeholder函數        if(!supportPlaceholder){            $(‘<input id="showpwd"  style="height: 45px; padding:6px 25px;line-height: 31px" type="text" class="form-control" placeholder="密碼">‘).appendTo(‘#pwdDiv‘);            $(‘#password‘).hide();            $(‘input‘).each(function(){                placeholder($(this))            });            $("input").focus(function () {                var placeTexr=$(this).attr("placeholder");                var value = $(this).attr("value");               // alert(placeTexr);                if($(this).attr("id") == "showpwd"){                    $(this).hide();                    $(‘#password‘).show().focus();                }else if($(this).attr("type") == "text" && $(this).val() ==placeTexr ){                    $(this).val("");                }            });            $("input").focusout(function () {                var placeTexr=$(this).attr("placeholder");                var test=$(this).val();                if($(this).attr("id") == "password" && $(this).val() == ""){                    $(this).hide();                    $(‘#showpwd‘).show();                }                if($(this).attr("type") == "text" && $(this).val() =="" ){                    $(this).val(placeTexr);                }            });        }    })($);

 

js解決IE8、9下placeholder的相容問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.