代码改变世界

让Placeholder在IE中燥起来

2015-10-26 11:27  只喝牛奶的杀手  阅读(1202)  评论(6编辑  收藏  举报

网上有好多关于这方面解决兼容性问题的文章,很多招式,学会这一招,让你轻松搞定Placeholder的兼容性,叫我好人,拿走,不谢。。。。

placeholder属性是HTML5 中为input添加的。在input上提供一个占位符,文字形式展示输入字段预期值的提示信息(hint),该字段会在输入为空时显示。

 <input type="text" id="Title" class="so-input-d w270" placeholder="请输入标题" />

像下图用placeholder刚刚好,但是IE6 7 8 9 不支持呀,一篇空白!此时此刻心情肯定是日了狗!!!!!,搞web开发的一定要考虑兼容性,业界良心需要。。。。

使用前:

使用后:

疗效不一般,使用之后萌萌哒。

目前浏览器的支持情况:

浏览器 IE6/7/8/9 IE10+ Firefox Chrome Safari 
是否支持 NO YES YES YES YES

 

 

下面分享一个Js文件代码,简单粗暴的把问题解决了:

 (function ($) {
    $.fn.myPlaceholder = function (options) {
        var defaults = {
            pColor: "#acacac",
            pFont: "16px",
            posL: 8,
            zIndex: "99"
        },
        opts = $.extend(true, defaults, options);

        if ("placeholder" in document.createElement("input")) return;
        return this.each(function () {
            //$(this).parent().css("position", "relative");
            var isIE = $.browser.msie,
            version = $.browser.version;

            //不支持placeholder的浏览器
            var $this = $(this),
                msg = $this.attr("placeholder"),
                iH = $this.outerHeight(),
                iW = $this.outerWidth(),
                iX = $this.offset().left,
                iY = $this.offset().top,
                oInput = $("<label>", {
                    "text": msg,
                    "css": {
                        "position": "absolute",
                        "left": iX + "px",
                        "top": iY + "px",
                        "width": iW - opts.posL + "px",
                        "padding-left": opts.posL + "px",
                        "height": iH + "px",
                        "line-height": iH + "px",
                        "color": opts.pColor,
                        "font-size": opts.pFont,
                        "z-index": opts.zIndex,
                        "cursor": "text"
                    }
                }).insertBefore($this);

            //初始状态就有内容
            var value = $this.val();
            if (value.length > 0) {
                oInput.hide();
            };
            var myEvent;
            if (isIE && version < 9) {
                myEvent = "propertychange";
            } else {
                myEvent = "input";
            }
            $this.bind(myEvent, function () {
                var value = $(this).val();
                if (value.length > 0) {
                    oInput.hide();
                } else {
                    oInput.show();
                }
            });
            oInput.click(function () {
                $this.trigger("focus");
            });
        });
    }
})(jQuery);

这是用JQUERY插件化思想的解决的!

在页面或者操作的Js文件只用这样轻轻一搞:

$(function () {
$("#Title").myPlaceholder();
});

Placeholder兼容问题就解决了(文章标红的地方注意ID一致)!

抓紧有限的时间,燥起来!