1

我知道有很多问题都有完整的答案,但我的情况有点不同。我正在尝试模拟“占位符”属性的确切行为,即-

1. 文本保持焦点不变

2.光标移动到文本的开头

3. 文本无法通过鼠标单击拖动或键盘的 shift-arrow 选择

4. 文字在按键或粘贴时消失

第 5 个显然是在提交时删除了“this”文本。

我想我已经完成了 '1' 和 '4' 的第 1 部分,但 '2'、'3' 和第 4 的第 2 部分(onpaste)仍然是一个问题...... :(

到目前为止我的jQuery....

$(document).ready(function(){
if(!Modernizr.input.placeholder){
    $('[placeholder]').keypress(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).keyup(function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).keyup();
    $('[placeholder]').parents('form').submit(function() {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });
    $('[placeholder]').focus(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
              //move the cursor to beginning
              //move the text unselectable
    }
});
}
});

对于第 2 次和第 3 次,我尝试过使用 onselectstart、setCursorPosition、setSelectionRange 等……但似乎没有按预期工作。对于 onpaste,我想用按键绑定它,但现在不知道在 w3schools 上该怎么做 bcoz 没有这样的事件属性:http: //www.w3schools.com/tags/ref_eventattributes.asp虽然在 MSDN 它显示:http ://msdn.microsoft.com/en-us/library/ie/ms536955%28v=vs.85%29.aspx

所以请帮忙!

4

1 回答 1

0

我建议一种不同的方法,使用 CSS 更改要显示在输入和 JS 上的标签的位置,仅在 IE 上,使标签可见。

(function ($) {

    $.fn.placeholder = function (options) {

        var options = $.extend({}, $.fn.placeholder.defaults, options);

        //show <label @for> for IE 
        if ($.browser.msie && $.browser.version < 10)
        {
            return this.each(function () {

                var $this = $(this);            

                $("label[for=" + $this.attr('id') + "]").show();

                //hide placeholder on focus
                $this.focus(function () {
                    if (!$.trim($this.val())) {
                        $("label[for=" + $this.attr('id') + "]").hide();
                    };
                });

                //show placeholder if the input is empty
                $this.blur(function () {
                    if (!$.trim($this.val())) {
                        $("label[for=" + $this.attr('id') + "]").show();
                    };
                });
            });
        }
    };

    //expose defaults
    $.fn.placeholder.defaults = {

    };
})(jQuery);
于 2012-10-28T11:12:00.993 回答