占位符不适用于Internet Explorer

时间:2022-03-20 17:25:30

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

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

有没有简单的方法只使用任何JavaScript。我不想使用jQuery使它变得复杂。

8 个解决方案

#1


50  

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 placeholder attribute, 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.

如果浏览器已经支持占位符属性,这将不起作用,并且如果它不受支持(例如浏览器是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 post it'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.

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

  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.

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

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

2014年1月24日:添加对

#2


3  

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-Polyfills and scroll down about 1/3 of the way to the section entitled Web Forms : input placeholder for 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 should still work even if you're not using the HTML5 doctype (no guarantees expressed or implied, etc.).

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

#3


3  

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

#4


1  

once i faced this problem

一旦我遇到这个问题

and this link http://bavotasan.com/2011/html5-placeholder-jquery-fix

这个链接http://bavotasan.com/2011/html5-placeholder-jquery-fix

will gives you a good solution

会给你一个很好的解决方案

#5


0  

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但并不复杂......

#6


0  

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!

似乎对我有用!

#7


0  

You can use a JavaScript Polyfill to 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使占位符在旧版浏览器上运行。那里有很多Polyfills。这是一个讨论让占位符在IE中工作的问题。基本上所有这些脚本所做的就是使用JavaScript模拟浏览器的本机占位符支持的行为。

#8


-1  

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>

#1


50  

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 placeholder attribute, 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.

如果浏览器已经支持占位符属性,这将不起作用,并且如果它不受支持(例如浏览器是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 post it'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.

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

  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.

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

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

2014年1月24日:添加对

#2


3  

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-Polyfills and scroll down about 1/3 of the way to the section entitled Web Forms : input placeholder for 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 should still work even if you're not using the HTML5 doctype (no guarantees expressed or implied, etc.).

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

#3


3  

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

#4


1  

once i faced this problem

一旦我遇到这个问题

and this link http://bavotasan.com/2011/html5-placeholder-jquery-fix

这个链接http://bavotasan.com/2011/html5-placeholder-jquery-fix

will gives you a good solution

会给你一个很好的解决方案

#5


0  

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但并不复杂......

#6


0  

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!

似乎对我有用!

#7


0  

You can use a JavaScript Polyfill to 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使占位符在旧版浏览器上运行。那里有很多Polyfills。这是一个讨论让占位符在IE中工作的问题。基本上所有这些脚本所做的就是使用JavaScript模拟浏览器的本机占位符支持的行为。

#8


-1  

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>