文本区域的Internet Explorer占位符

Internet Explorer Placeholder For Textarea

本文关键字:Explorer 占位符 Internet 区域 文本      更新时间:2023-09-26

我的应用程序需要文本字段和文本区域字段的占位符。我知道Internet Explorer不支持占位符。我环顾四周,发现了一些后备代码,它只适用于文本字段。我如何才能让这也适用于文本区域。

代码:

jQuery(function() {
    jQuery.support.placeholder = false;
    test = document.createElement('input');
    if('placeholder' in test) jQuery.support.placeholder = true;
});
$(function() {
    if(!$.support.placeholder) { 
        var active = document.activeElement;
        $('input[type=text], textarea').focus(function () {
            if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
                $(this).val('').removeClass('hasPlaceholder');
            }
        }).blur(function () {
            if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
                $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
            }
        });
        $('input[type="text"], textarea').blur();
        $(active).focus();
        $('form').submit(function () {
            $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
        });
    }
});

HTML:

                <li>
                    <input type="text" placeholder="To:" id="to" autocapitalize="off" autocorrect="off" autocomplete="off" />
                </li>
                <li>
                    <textarea placeholder="Message:" id="body" rows="10" cols="30" autocapitalize="off" autocorrect="off" autocomplete="off"></textarea>
                </li>

$(':text')更改为$('input[type="text"], textarea')

或者,这个现有的jQuery插件:

https://github.com/mathiasbynens/jquery-placeholder

适用于文本区域和许多类型的输入字段,包括密码字段

<script type="text/javascript">
 $(function() {
    if(!$.support.placeholder) { 
        var active = document.activeElement;
        $('input[type="text"], textarea').focus(function () {
            if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
                $(this).val('').removeClass('hasPlaceholder');
            }
        }).blur(function () {
            if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
                $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
            }
        });
        $('input[type="text"], textarea').blur();
        $(active).focus();
        $('form').submit(function () {
            $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
        });
    }
});
</script>

它正在使用文本选择器,将其更改为也使用文本区域。

$(':text')

应该是

$(':text, textarea')

或者为了获得更好的性能,请使用

$('input[type=text], textarea')

看起来您需要用:text,textarea替换:text