使用JavaScript取消选择文本框中的内容

14

我明白使用 JavaScript 可以使用以下代码(在 jQuery 中)选择文本框的内容:

$("#txt1").select();

有没有办法做相反的事情?取消选择文本框的内容?我已经将一系列文本框的焦点事件设置为选择它们内部的内容。现在有时候我想要聚焦到一个特定的文本框,但是不选中它。我计划做的是调用这个特定文本框的焦点事件,然后跟着再调用一个取消选中的事件。

$("input[type=text]").focus(function() {
    $(this).select();
});

//code....

$("#txt1").focus();

//some code here to deselect the contents of this textbox
任何想法?
谢谢!
8个回答

19

这个怎么样:

$("input").focus(function(){
  this.selectionStart = this.selectionEnd = -1;
});

火狐在运行缓慢时占用了1.5GB的内存,难道是这个原因吗?在我执行"kill -9"命令之前,我的火狐经常会这样。 - mkoryak

8
如果您只是将文本框的值分配给其自身,它应该取消选择文本。

3
您需要设置selectionStartselectionEnd属性。但由于某些原因,在焦点事件中设置这些属性不起作用(我不知道为什么)。要使其起作用,请在小间隔后设置这些属性。
  $(document).ready(function(){
    $('#txt1').focus(function(){
      setTimeout(function(){
        // set selection start, end to 0
        $('#txt1').attr('selectionStart',0);
        $('#txt1').attr('selectionEnd',0);
      },50);  // call the function after 50ms
    });
  });

1
关于“聚焦特定文本框而不选择它”: 我会使用修补的jquery插件jquery-fieldselection的一部分。
使用它,你可以调用。
$('#my_text_input').setSelection({"start":0, "end":0}); // leaves the cursor at the left

或者使用这个缩减版,将光标默认放在文字末尾

(function() {
var fieldSelection = {
    setSelection: function() {
        var e = (this.jquery) ? this[0] : this, len = this.val().length || ;
        var args = arguments[0] || {"start":len, "end":len};
        /* mozilla / dom 3.0 */
        if ('selectionStart' in e) {
            if (args.start != undefined) {
                e.selectionStart = args.start;
            }
            if (args.end != undefined) {
                e.selectionEnd = args.end;
            }
            e.focus();
        }
        /* exploder */
        else if (document.selection) {
            e.focus();
            var range = document.selection.createRange();
            if (args.start != undefined) {
                range.moveStart('character', args.start);
                range.collapse();
            }
            if (args.end != undefined) {
                range.moveEnd('character', args.end);
            }
            range.select();
        }
        return this;
    }
};
jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });
})();

使用方法如下:

$('#my_text_input').setSelection(); // leaves the cursor at the right

0

这是一个不需要jquery的简单解决方案

<input type="text" onblur="this.selectionStart = this.selectionEnd = -1;">

0
为什么不在DOM元素上暂时存储一个布尔值,而不是选择然后取消选择呢?
 $("input[type=text]").focus(function() {
     if($(this).skipFocus) return;
     $(this).select();
 });

 //code....

 $("#txt1").skipFocus = true;
 $("#txt1").focus();

0

我想建议一个简单的解决方案

$("input[type=text]").focus(function() {
    $(this).select();
});

$("input[type=text]").blur(function() {
    $('input[type="hidden"][value=""]').select();
});

//code....

$("#txt1").focus();

-1
如果您想使用jQuery取消选择文本框,请执行以下操作:
   $(your_input_selector).attr('disabled', 'disabled');
   $(your_input_selector).removeAttr('disabled');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接