js解决IE89下placeholder的兼容问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js解决IE89下placeholder的兼容问题相关的知识,希望对你有一定的参考价值。

由于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解决IE89下placeholder的兼容问题的主要内容,如果未能解决你的问题,请参考以下文章

关于input 属性placeholder 在IE9下兼容

jquery.placeholder.js解决IE8兼容h5中input属性placeholder属性

解决输入框placeholder属性不兼容IE9及以下浏览器问题

兼容ie10以下版本的placeholder属性

低版本IE内核浏览器兼容placeholder属性解决办法

IE9及以下兼容placeholder