Html 占位符不适用于 Internet Explorer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8628522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:09:34  来源:igfitidea点击:

Placeholder not working for Internet Explorer

html

提问by Mad coder.

Placeholder for my textbox in below format is not working for Internet Explorer. Is there anyway to display placeholder for TextBox in Internet Explorer?

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

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

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

Is there any simple way just by using any JavaScript. I am not interested to make it complicated using jQuery.

是否有任何简单的方法只使用任何 JavaScript。我没有兴趣使用 jQuery 让它变得复杂。

回答by Shadow Wizard is Ear For You

You can imitate this using pure JavaScript:

你可以使用纯 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 />";
    }
}

This will do nothing if the browser is already supporting the placeholderattribute, and in case it's not supported (e.g. the browser is IE) it will add very similar functionality - text shown by default that disappear on focus and appears again if user didn't type anything.

如果浏览器已经支持该placeholder属性,这将什么都不做,如果它不受支持(例如浏览器是 IE),它将添加非常相似的功能 - 默认显示的文本会在焦点上消失,如果用户没有输入则再次出现任何事物。

Live test case.

现场测试用例

Bug Fixes

Bug修复

Nov 6, 2012: Previous code failed to detect when browser didn't have native support for placeholder. Using code found in this other postit's now fixed. Affected browsers: IE7 and IE8, maybe others as well. Also added debug support to help debug future problems.

2012 年 11 月 6 日:当浏览器没有对占位符的本机支持时以前的代码无法检测到。使用在另一篇文章中找到的代码现在已修复。受影响的浏览器:IE7 和 IE8,也许还有其他浏览器。还添加了调试支持以帮助调试未来的问题。

Jan 30, 2013:

2013 年 1 月 30 日

  1. Adding support for password input as well. Since IE8 and below won't allow dynamic change of input type, the code is replacing the password input with text input as long as there is no password typed, thus the placeholder text will be visible.

  2. Fixed bug that caused the placeholder value to be sent where empty value should be sent to the server when the form associated with the input is being submitted. To achieve this, code is attached to the form submit event and clear the value if needed.

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

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

Jan 24, 2014: adding support for <textarea>elements.

2014 年 1 月 24 日:添加对<textarea>元素的支持。

回答by Ephra

I have written this simple code, and it worked fine for me when tested:

我写了这个简单的代码,经过测试,它对我来说很好用:

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);

回答by Scott

There are a number of polyfill scripts written that will add placeholder support to browsers that don't natively support the technology.

有许多编写的 polyfill 脚本将为不原生支持该技术的浏览器添加占位符支持。

Rather than repeating what's been written elsewhere, I'd recommend going here: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfillsand scroll down about 1/3 of the way to the section entitled Web Forms : input placeholderfor a few different options (both native JS and jQuery). Since that entire page is curated by the HTML5 Boilerplate team you can be fairly certain that the scripts provided are of decent quality.

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

Edit: just saw your comment about not using HTML5. The scripts on the link I provided shouldstill work even if you're not using the HTML5 doctype (no guarantees expressed or implied, etc.).

编辑:刚刚看到您关于不使用 HTML5 的评论。我提供的链接中的脚本应该,如果你不使用HTML5的doctype(没有明示或暗示的保证等),甚至还在工作。

回答by Tiji

You can use a JavaScript Polyfillto make the placeholder work on older browsers. There are many Polyfills out there. Here is one that talks about Making Placeholders work in IE. Basically what all these Scripts do is to Simulate the behaviour of a native placeholder support of browser using JavaScript.

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

回答by Andrew Samuelsen

Placeholder is an HTML5 feature. To work around I detect MSIE and do this:

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

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

Its jquery but not that complicated...

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

回答by Jon Stevens

I have had this issue recently - I use modernizr to detect html5 features and then run a bit of js for the browsers that can't cope:

我最近遇到了这个问题 - 我使用 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'));

seems to work well for me!

似乎对我来说效果很好!

回答by Darshan marathe

Just grabbed the code from above and made it more generic

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

<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>