11

在我使用.select()鼠标悬停在输入框中选择文本后,我执行了以下操作:

HTML:

<input type="text" class="hoverAble" value="hover here"/><br />

jQuery:

$(".hoverAble").mouseenter(function() {

    this.select();

}).mouseleave(function() {

    //I can't figure what to put here.
});

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

主要思想是也按预期mouseleave工作。

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

在此处输入图像描述

4

6 回答 6

12

采用.blur();

http://jsfiddle.net/robert/adCfw/6/

于 2011-05-02T19:09:57.613 回答
8

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

$(".hoverAble").mouseenter(function() {
    this.select();
}).mouseleave(function() {
    $(this).prop('selectionStart', 0).prop('selectionEnd',0).blur();
});
于 2018-10-06T02:34:36.587 回答
2

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

$(this).blur();
于 2011-05-02T19:10:48.263 回答
1

这有效:

$(".hoverAble").hover(function() {

    $(this).select();
    $(this).after("<input type='text' style='height:0;width:0;border:0;padding:0;margin:0;' id='tmp_hidden' />");

}, function(){

    $("#tmp_hidden").select().remove();

});

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

编辑:当然有blur().

于 2011-05-02T19:13:49.563 回答
1
input.hover(function(){$(this).select();}, function(){$(this).val($(this).val());});
于 2012-06-06T06:31:32.293 回答
0

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

于 2018-04-06T08:08:28.210 回答