由于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);
                }
            });
        }
    })($);

 

 posted on 2016-10-13 11:17  沫沫小青  阅读(249)  评论(0编辑  收藏  举报