改进《完美让IE兼容input placeholder属性的jquery实现》的不完美

时间:2023-11-10 15:46:20

《完美让IE兼容input placeholder属性的jquery实现》中的代码在IE9以下浏览器中会出错,原因是因为ie9以下的浏览器对input的标签的解释不同。

例如对以下文本框的解释:

<input id="itxt" class="itext" type="text" title="这是一个文本框" value="点我输入内容" tabindex="1" maxlength="20">

  

IE7:

<INPUT id=itxt class=itext title=这是一个文本框 tabIndex=1 maxLength=20 value=点我输入内容>

  

IE8:

<INPUT id=itxt class=itext title=这是一个文本框 tabIndex=1 maxLength=20 value=点我输入内容 type=text>

  

IE9:

<input id="itxt" class="itext" title="这是一个文本框" tabIndex="1" maxLength="20" value="点我输入内容" type="text">

  

对于这样不同的解释,我只想说IE去死。不过从IE9开始,似乎IE正在拼命做到不去死了,这多少让我们这些苦逼的Coder们有些欣慰。

而《完美让IE兼容input placeholder属性的jquery实现》的不完美正是因为我们的正则无法验证这些IE的不同所致。

下面给出完美的方案:

/*
* 球到西山沟
* http://www.cnzj5u.com
* 2014/11/26 12:12
*/
(function ($) {

    //判断是否支持placeholder
    function isPlaceholer() {
        var input = document.createElement("input");
        return "placeholder" in input;
    }

    var placeholderfriend = {
        focus: function (s) {
            s = $(s).hide().prev().show().focus();
        }
    }

    //不支持的代码
    if (!isPlaceholer()) {
        $(function () {
            var form = $(this);

            var elements = form.find("input[placeholder]");

            elements.each(function () {
                var s = $(this);
                var pValue = s.attr("placeholder");
                var sValue = s.val();
                if (pValue) {
                    if (sValue == "") {
                        //DOM不支持type的修改,需要复制密码框属性,生成新的DOM
                        var newinputstr = s.prop('outerHTML') || "";
                        newinputstr = newinputstr.replace(/type[" "]*=[" "]*password[" "]*/g, " type=\"text\" ")
                            .replace(/type[" "]*=[" "]*[']\s*password[" "]*['][" "]*/g, " type=\"text\" ")
                            .replace(/type[" "]*=[" "]*["\""]password[" "]*["\""]/g, " type=\"text\" ");
                        newinput = $(newinputstr);
                        newinput.attr("value", s.attr("placeholder")).css("color", "#a9a9a9").focus(function() {
                            placeholderfriendfocus(this);
                        });
                        s.hide();
                        s.after(newinput);
                    }
                }
            });

            elements.blur(function () {
                var s = $(this);
                var sValue = s.val();
                if (sValue == "") {
                    s.hide().next().show();
                }
            });

        });
    }
    window.placeholderfriendfocus = placeholderfriend.focus;
})(jQuery);