解决IE9及以下版本对placeholder的兼容性问题

解决IE9及以下版本对placeholder的兼容性问题

placeholder属性可以对input输入框输入内容的提醒或者指引
但在IE9及IE9以下不支持 placeholder 属性

优化示例:
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简单实现IE9及以下对placeholder的兼容性</title>
<style>
    *{margin: 0;padding: 0;font-family: "Microsoft YaHei";font-size: 14px;}
    .placeholder {position: absolute;top: 8px;padding-left: 74px;z-index: 10;color: #888;}
</style>
</head>
<body>
<div>
    <input  id="eqpCod" name="设备号" placeholder="设备号批量查询,用英文逗号隔开"/>
</div>
<script src="jquery-1.11.3.js"></script>
<script>
    $(function(){
        // 兼容IE9下的placeholder
        function placeholderSupport() {
            return 'placeholder' in document.createElement('input');
        }
        if(!placeholderSupport()){   // 判断浏览器是否支持 placeholder
            $("[placeholder]").each(function(){
                var _this = $(this);
                var left = _this.css("padding-left");
                _this.parent().append('<span class="placeholder" data-type="placeholder" style="left: ' + left + '">' + _this.attr("placeholder") + '</span>');
                if(_this.val() != ""){
                    _this.parent().find("span.placeholder").hide();
                }
                else{
                    _this.parent().find("span.placeholder").show();
                }
            }).on("focus", function(){
                $(this).parent().find("span.placeholder").hide();
            }).on("blur", function(){
                var _this = $(this);
                if(_this.val() != ""){
                    _this.parent().find("span.placeholder").hide();
                }
                else{
                    _this.parent().find("span.placeholder").show();
                }
            });
            // 点击表示placeholder的标签相当于触发input
            $("span.placeholder").on("click", function(){
                $(this).hide();
                $(this).siblings("[placeholder]").trigger("click");
                $(this).siblings("[placeholder]").trigger("focus");
            });
        }
    })
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_38887752/article/details/84957770