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

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

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

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

 $("input[type=text]").focus(function() { $(this).select(); }); //code.... $("#txt1").focus(); //some code here to deselect the contents of this textbox 

有任何想法吗?

谢谢!

那这个呢:

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

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

您需要设置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 }); }); 

要“聚焦特定文本框而不选择它”:我将使用修补的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 

而不是选择然后取消选择,为什么不在dom元素上暂时存储一个布尔值?

  $("input[type=text]").focus(function() { if($(this).skipFocus) return; $(this).select(); }); //code.... $("#txt1").skipFocus = true; $("#txt1").focus(); 

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

 $("input[type=text]").focus(function() { $(this).select(); }); $("input[type=text]").blur(function() { $('input[type="hidden"][value=""]').select(); }); //code.... $("#txt1").focus(); 

这是一个没有jquery的简单解决方案

  

如果要使用jQuery取消选择文本框,请执行以下操作:

  $(your_input_selector).attr('disabled', 'disabled'); $(your_input_selector).removeAttr('disabled');