使用.select()取消选择输入中选择的内容

在我使用.select()选择输入框中的文本时,我执行以下操作:

HTML:

 

jQuery的:

 $(".hoverAble").mouseenter(function() { this.select(); }).mouseleave(function() { //I can't figure what to put here. }); 

看到这里 。 警告它正常运行(在jsfiddle中)你必须在结果框中单击一次。

主要思想是mouseleave 正如预期的那样工作。

正如您可能已经注意到的那样,当您将鼠标hover时我无法找到取消选择文本的方法并避免这种情况:

在此处输入图像描述

如果您使用的是jQuery,请尝试使用blur()。

 $(this).blur(); 

这有效:

 $(".hoverAble").hover(function() { $(this).select(); $(this).after(""); }, function(){ $("#tmp_hidden").select().remove(); }); 

应该有更好的方法来解决它。

编辑:当然有blur()

 input.hover(function(){$(this).select();}, function(){$(this).val($(this).val());}); 

如果你使用jQuery,你可以尝试使用众多插件中的一个来取消选择或根据你的需要设置插入位置,例如这个 。 如果不这样做,由于开源许可证,您仍然可以使用这些插件的纯JavaScript

在这种情况下,blur()仅从输入文本中取消聚焦,虽然它给出了外观,但不再选择文本,但它仍然被选中。 要真正取消选择任何文本,您可以:

 $(".hoverAble").mouseenter(function() { this.select(); }).mouseleave(function() { $(this).prop('selectionStart', 0).prop('selectionEnd',0).blur(); });