函数来替换占位符文本

Function to replace placeholder text

本文关键字:文本 占位符 替换 函数      更新时间:2024-03-08

我们创建了一个函数来替代字段中的占位符文本,如果浏览器不支持占位符属性(即早期的IE浏览器),则该函数应运行。

然而,它似乎不起作用,我们也无法找出原因。你能看看怎么了吗?

setup_placeholders = (function() {
    $.support.placeholder = false;
    test = document.createElement('input');
    if('placeholder' in test) {
        $.support.placeholder = true;
        return function() {}
    } else {
        return function(){
            $(function() {
                var active = document.activeElement;
                $('form').delegate(':text', 'focus', function () {
                    var _placeholder = $(this).attr('placeholder'),
                        _val = $(this).val();
                    if (_placeholder != '' && _val == _placeholder) {
                        $(this).val('').removeClass('hasPlaceholder');
                    }
                }).delegate(':text', 'blur', function () {
                    var _placeholder = $(this).attr('placeholder'),
                        _val = $(this).val();
                    if (!_placeholder && ( _val == '' || _val == _placeholder)) {
                        $(this).val(_placeholder).addClass('hasPlaceholder');
                    }
                }).submit(function () {
                    $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
                });
                $(':text').blur();
                $(active).focus();
            });
        }
    }
})();
JQuery方法:
(function($) {
    var safe = [];
    $.fn.store = function() {
        safe[$(this).attr('id')] = $(this).val();
        $(this).click(function() {if ($(this).val() == safe[$(this).attr('id')]) $(this).val('');});
        $(this).blur(function() {if ($(this).val() == '') $(this).val(safe[$(this).attr('id')]);});
    };
}( jQuery ));

用法:

<input type="text" id="txt_field" name="txt_field" value="Placeholder">
<script>
    $('#txt_field').store();
</script>