IE中不支持占位符属性.有什么建议?

Chr*_*ini 20 html jquery html5 internet-explorer

您在浏览器中使用什么来支持占位符属性?

目前,我正在使用:

https://github.com/mathiasbynens/Placeholder-jQuery-Plugin

也试过这个插件无济于事:

https://github.com/danbentley/placeholder

但它似乎不适用于IE ...更具体地说是IE 8.任何其他建议/备选方案?

我现在应该忘记占位符属性吗?

Spu*_*ley 14

你是对的,IE8不支持该placeholder属性.placeholder是HTML5规范的一部分,IE8在HTML5被人们想到之前发布了很长时间.

以无缝方式处理它的最佳方法是使用Modernizr之类的工具来检测浏览器是否支持占位符功能,如果不支持则运行JS polyfill脚本.

if(!Modernizr.input.placeholder) {
    //insert placeholder polyfill script here.
}
Run Code Online (Sandbox Code Playgroud)

有许多占位符polyfill脚本可供下载.选择一个使用该placeholder属性的方法,这样您只需要在一个地方为所有浏览器定义占位符字符串.这是你可以尝试的:http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

希望有所帮助.


Dyl*_*yes 6

这里的代码直接来自我的项目,它本身在chrome中运行并使用IE8中的polyfill ...这里有一个警告,用于测试,显示何时调用polyfill.您需要加载modernizr作为使用此代码的先决条件,但您的<head>部分中将包含一个简单的脚本.

<script type="text/javascript">
    $('document').ready(function () {
        if (!Modernizr.input.placeholder) {
            $('[placeholder]').focus(function() {
                var input = $(this);
                if (input.val() == input.attr('placeholder')) {
                    input.val('');
                    input.removeClass('placeholder');
                }
            }).blur(function() {
                var input = $(this);
                if (input.val() == '' || input.val() == input.attr('placeholder')) {
                    input.addClass('placeholder');
                    input.val(input.attr('placeholder'));
                   }
            }).blur();

            $('[placeholder]').parents('form').submit(function() {
                $(this).find('[placeholder]').each(function() {
                    var input = $(this);
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                })
            });

            alert("no place holders");
        }
    });
</script>
Run Code Online (Sandbox Code Playgroud)