【问题标题】:Placeholder not working for Internet Explorer占位符不适用于 Internet Explorer
【发布时间】:2012-01-27 13:11:10
【问题描述】:

以下格式的文本框占位符不适用于 Internet Explorer。无论如何在 Internet Explorer 中显示 TextBox 的占位符?

<asp:TextBox id="email" runat="server" width="300" placeholder="Your email" />

是否有任何简单的方法,只需使用任何 JavaScript。我不想用 jQuery 让它变得复杂。

【问题讨论】:

标签: html


【解决方案1】:

您可以使用纯 JavaScript 来模仿:

var _debug = false;
var _placeholderSupport = function() {
    var t = document.createElement("input");
    t.type = "text";
    return (typeof t.placeholder !== "undefined");
}();

window.onload = function() {
    var arrInputs = document.getElementsByTagName("input");
    var arrTextareas = document.getElementsByTagName("textarea");
    var combinedArray = [];
    for (var i = 0; i < arrInputs.length; i++)
        combinedArray.push(arrInputs[i]);
    for (var i = 0; i < arrTextareas.length; i++)
        combinedArray.push(arrTextareas[i]);
    for (var i = 0; i < combinedArray.length; i++) {
        var curInput = combinedArray[i];
        if (!curInput.type || curInput.type == "" || curInput.type == "text" || curInput.type == "textarea")
            HandlePlaceholder(curInput);
        else if (curInput.type == "password")
            ReplaceWithText(curInput);
    }

    if (!_placeholderSupport) {
        for (var i = 0; i < document.forms.length; i++) {
            var oForm = document.forms[i];
            if (oForm.attachEvent) {
                oForm.attachEvent("onsubmit", function() {
                    PlaceholderFormSubmit(oForm);
                });
            }
            else if (oForm.addEventListener)
                oForm.addEventListener("submit", function() {
                    PlaceholderFormSubmit(oForm);
                }, false);
        }
    }
};

function PlaceholderFormSubmit(oForm) {    
    for (var i = 0; i < oForm.elements.length; i++) {
        var curElement = oForm.elements[i];
        HandlePlaceholderItemSubmit(curElement);
    }
}

function HandlePlaceholderItemSubmit(element) {
    if (element.name) {
        var curPlaceholder = element.getAttribute("placeholder");
        if (curPlaceholder && curPlaceholder.length > 0 && element.value === curPlaceholder) {
            element.value = "";
            window.setTimeout(function() {
                element.value = curPlaceholder;
            }, 100);
        }
    }
}

function ReplaceWithText(oPasswordTextbox) {
    if (_placeholderSupport)
        return;
    var oTextbox = document.createElement("input");
    oTextbox.type = "text";
    oTextbox.id = oPasswordTextbox.id;
    oTextbox.name = oPasswordTextbox.name;
    //oTextbox.style = oPasswordTextbox.style;
    oTextbox.className = oPasswordTextbox.className;
    for (var i = 0; i < oPasswordTextbox.attributes.length; i++) {
        var curName = oPasswordTextbox.attributes.item(i).nodeName;
        var curValue = oPasswordTextbox.attributes.item(i).nodeValue;
        if (curName !== "type" && curName !== "name") {
            oTextbox.setAttribute(curName, curValue);
        }
    }
    oTextbox.originalTextbox = oPasswordTextbox;
    oPasswordTextbox.parentNode.replaceChild(oTextbox, oPasswordTextbox);
    HandlePlaceholder(oTextbox);
    if (!_placeholderSupport) {
        oPasswordTextbox.onblur = function() {
            if (this.dummyTextbox && this.value.length === 0) {
                this.parentNode.replaceChild(this.dummyTextbox, this);
            }
        };
    }
}

function HandlePlaceholder(oTextbox) {
    if (!_placeholderSupport) {
        var curPlaceholder = oTextbox.getAttribute("placeholder");
        if (curPlaceholder && curPlaceholder.length > 0) {
            Debug("Placeholder found for input box '" + oTextbox.name + "': " + curPlaceholder);
            oTextbox.value = curPlaceholder;
            oTextbox.setAttribute("old_color", oTextbox.style.color);
            oTextbox.style.color = "#c0c0c0";
            oTextbox.onfocus = function() {
                var _this = this;
                if (this.originalTextbox) {
                    _this = this.originalTextbox;
                    _this.dummyTextbox = this;
                    this.parentNode.replaceChild(this.originalTextbox, this);
                    _this.focus();
                }
                Debug("input box '" + _this.name + "' focus");
                _this.style.color = _this.getAttribute("old_color");
                if (_this.value === curPlaceholder)
                    _this.value = "";
            };
            oTextbox.onblur = function() {
                var _this = this;
                Debug("input box '" + _this.name + "' blur");
                if (_this.value === "") {
                    _this.style.color = "#c0c0c0";
                    _this.value = curPlaceholder;
                }
            };
        }
        else {
            Debug("input box '" + oTextbox.name + "' does not have placeholder attribute");
        }
    }
    else {
        Debug("browser has native support for placeholder");
    }
}

function Debug(msg) {
    if (typeof _debug !== "undefined" && _debug) {
        var oConsole = document.getElementById("Console");
        if (!oConsole) {
            oConsole = document.createElement("div");
            oConsole.id = "Console";
            document.body.appendChild(oConsole);
        }
        oConsole.innerHTML += msg + "<br />";
    }
}

如果浏览器已经支持placeholder 属性,这将不起作用,并且如果不支持它(例如浏览器是 IE),它将添加非常相似的功能 - 默认显示的文本在焦点上消失并再次出现如果用户没有输入任何内容。

Live test case.

错误修复

2012 年 11 月 6 日:之前的代码未能检测到浏览器何时不具备对占位符的原生支持。使用找到的代码in this other post 现在已修复。受影响的浏览器:IE7 和 IE8,可能还有其他浏览器。还添加了调试支持以帮助调试未来的问题。

2013 年 1 月 30 日:

  1. 还添加了对密码输入的支持。由于 IE8 及以下版本不允许动态更改输入类型,代码将密码输入替换为文本输入,只要没有输入密码即可,因此占位符文本将可见。

  2. 修复了在提交与输入关联的表单时应将空值发送到服务器的占位符值被发送的错误。为此,将代码附加到表单提交事件并在需要时清除该值。

2014 年 1 月 24 日:添加对 &lt;textarea&gt; 元素的支持。

【讨论】:

  • 哇,谢谢,我在整个互联网上寻找可以在 IE 中使用的占位符后备。最后,就是这个。
  • @ShadowWizard 这对我来说在 IE7 或 IE8 中不起作用。它适用于 IE9,但不适用于密码输入。
  • @Mark 抱歉耽搁了,没有收到您的评论通知。发现并修复了错误,它现在也可以在这些浏览器上运行。感谢您的提醒!
  • @ZainShaikh 希望我的修复程序也能解决该浏览器的问题,我无法访问此类浏览器,所以请告诉我。如果仍然无法正常工作,请更改为 _debug = true; 并在此处发布调试结果。谢谢!
  • 先生,你用这个脚本为我提供了很好的服务,我已经辛勤工作了好几天来解决这个问题,我需要一个漂亮的脚本,我只需要剪切、粘贴和繁荣。有用。我感激不尽!
【解决方案2】:

已经编写了许多 polyfill 脚本,它们将为不原生支持该技术的浏览器添加占位符支持。

与其重复在其他地方写的内容,我建议您访问这里:https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills 并向下滚动大约 1/3 到标题为 Web 表单:输入占位符的部分不同的选项(原生 JS 和 jQuery)。由于整个页面都是由 HTML5 Boilerplate 团队策划的,因此您可以相当肯定所提供的脚本质量不错。

编辑:刚刚看到您关于不使用 HTML5 的评论。即使您不使用 HTML5 文档类型,我提供的链接上的脚本应该仍然有效(没有明示或暗示的保证等)。

【讨论】:

    【解决方案3】:

    我已经编写了这个简单的代码,并且在测试时对我来说效果很好:

    placeholder=function(){
        $('input, textarea').each(function(){
            var holder=$(this).attr('placeholder');
            if(typeof(holder) !=='undefined'){
                $(this).val(holder);
                $(this).bind('click',function(){
                    $(this).val('');
                }).blur(function(){
                    $(this).val(holder);
                });
            }
        });
    };
    $(document).ready(placeholder);
    

    【讨论】:

    • 您的代码在 ie 中运行,但在 FF 和 GC 浏览器中出现问题,即占位符文本变为粗体,如果我单击输入框中出现的正常字体,我无法看到输入数据。为了调试,我从底部删除了准备好的 DOM 并在顶部添加,FF 和 GC 中的问题似乎很好,但占位符不在 IE 中。
    • 好东西!但我已将函数初始化置于if( $.browser.msie &amp;&amp; $.browser.version &lt;= '9.0' ) 之类的条件下。非常感谢!
    【解决方案4】:

    占位符是一项 HTML5 功能。为了解决这个问题,我检测到 MSIE 并执行以下操作:

    if ( $.browser.msie ) {
        $("#textarea-id").val('placeholder');
        $("#textarea-id").focus(function(){
            this.select();
        });
    }
    

    它的 jquery 但没那么复杂...

    【讨论】:

    • 它可能没有那么复杂,但是为什么只使用一个 31kB 的库来完成这个极其简单的任务呢?几百字节的纯 JS 对我来说似乎更干净 :)
    • @Madcoder。如果您使用的是占位符,那么您使用的是 HTML5。
    【解决方案5】:

    我最近遇到了这个问题-我使用modernizr来检测html5功能,然后为无法应对的浏览器运行一点js:

        function addPlaceHolder(input) {//using modernizr add placeholder text for non html5 users
        if (!Modernizr.input.placeholder) { 
            input.focus(function () {
                if (input.val() == input.attr('placeholder')) {
                    input.val('');
                    input.removeClass('placeholder');
                }
            }).blur(function () {
                if (input.val() == '' || input.val() == input.attr('placeholder')) {
                    input.addClass('placeholder');
                    input.val(input.attr('placeholder'));
                }
            }).blur();
            $(input).parents('form').submit(function () {
                $(this).find(input).each(function () {
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                })
            });
        }
    }
    
    addPlaceHolder($('#Myinput'));
    

    似乎对我很有效!

    【讨论】:

      【解决方案6】:

      您可以使用JavaScript Polyfill 使占位符在旧版浏览器上工作。那里有很多 Polyfills。这是一个关于Making Placeholders work in IE 的讨论。基本上所有这些脚本所做的是使用 JavaScript 模拟浏览器的原生占位符支持的行为。

      【讨论】:

        【解决方案7】:

        刚刚从上面抓取代码并使其更通用

        <script type="text/javascript">
        
        
        function addPlaceHolder(input) {
        
            if (!Modernizr.input.placeholder) {
                input.focus(function () {
                    if ($(this).val() == $(this).attr('placeholder')) {
                        $(this).val('');
                        $(this).removeClass('placeholder');
                    }
                }).blur(function () {
                    if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')) {
                        $(this).addClass('placeholder');
                        $(this).val($(this).attr('placeholder'));
                    }
                }).blur();
                $(input).parents('form').submit(function () {
                    $(this).find(input).each(function () {
                        if ($(this).val() == $(this).attr('placeholder')) {
                            $(this).val('');
                        }
                    })
                });
             }
         }
        
            addPlaceHolder($(':text'));
            addPlaceHolder($('textarea'));
        
        </script>
        

        【讨论】:

        • 原帖说不想用jQuery。
        猜你喜欢
        • 2011-07-28
        • 2014-11-24
        • 2017-07-23
        • 2013-02-27
        • 1970-01-01
        • 2013-11-12
        • 2013-07-20
        • 1970-01-01
        相关资源
        最近更新 更多