让 IE 8 及以下浏览器支持 表单 input [placeholder] 属性

 

在我们的日常开发中,时常会遇到要求兼容 ie低版本 的项目,其中表单多的项目,其中 用到 placeholder 属性几乎是必不可少的。

placeholder是一个很实用的Html 5属性。但是该属性在低版本的IE下是无效的。

于是在网上找了很多方法,就以下方法,比较简单方便。

 

首先新建一个js文件,把下方代码,放到一个JS文件里面,页面直接引入即可。

//解决ie下 input 的placeholder不显示问题
var JPlaceHolder = {
    //检测
    _check: function() {
        return 'placeholder' in document.createElement('input');
    },
    //初始化
    init: function() {
        if(!this._check()) {
            this.fix();
        }
    },
    //修复
    fix: function() {
        jQuery(':input[placeholder]').each(function(index, element) {
            var self = $(this),
                txt = self.attr('placeholder');
            self.wrap($('<div></div>').css({
                display:'inline-block',
                position: 'relative',
                zoom: '1',
                border: 'none',
                background: 'none',
                padding: 'none',
                margin: 'none'
            }));
            var pos = self.position(),
                h = self.outerHeight(true),
                paddingleft = self.css('padding-left');
            var holder = $('<span></span>').text(txt).css({
                position: 'absolute',
                left: pos.left,
                top: pos.top,
                height: h,
                lineHeight: h +"px",
                paddingLeft: paddingleft,
                color: '#aaa'
            }).appendTo(self.parent());
            self.focusin(function(e) {
                holder.hide();
            }).focusout(function(e) {
                if(!self.val()) {
                    holder.show();
                }
            });
            holder.click(function(e) {
                holder.hide();
                self.focus();
            });
            console.log(h)
        });
    }
};
//执行
jQuery(function() {
    JPlaceHolder.init();
});

 

 

希望可以帮助到你。

by不言谢

posted @ 2020-01-26 16:03  不言谢  阅读(236)  评论(0编辑  收藏  举报