码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-01-26 17:31:26      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:relative   code   console   style   doc   Fix   低版本   border   oom   

 

在我们的日常开发中,时常会遇到要求兼容 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不言谢

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

标签:relative   code   console   style   doc   Fix   低版本   border   oom   

原文地址:https://www.cnblogs.com/byx1024/p/12234322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!