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

Dan*_*ard 11 javascript jquery dom focus

我理解使用javascript你可以使用以下代码选择文本框的内容(在jQuery中):

$("#txt1").select();
Run Code Online (Sandbox Code Playgroud)

有没有办法做相反的事情?要取消选择文本框的内容?我有一系列文本框的焦点事件,用于选择其中的内容.现在有时候我想要关注特定的文本框而不选择它.我打算做的是为这个特定的文本框调用焦点事件,然后通过调用取消选择它.

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

//code....

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

//some code here to deselect the contents of this textbox
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

谢谢!

mko*_*yak 18

那这个呢:

$("input").focus(function(){
  this.selectionStart = this.selectionEnd = -1;
});
Run Code Online (Sandbox Code Playgroud)


Bra*_*don 8

如果只是将文本框的值分配给自身,则应取消选择文本.