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

Tru*_*ufa 9 jquery select hover unselect

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

HTML:

<input type="text" class="hoverAble" value="hover here"/><br />
Run Code Online (Sandbox Code Playgroud)

jQuery的:

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

    this.select();

}).mouseleave(function() {

    //I can't figure what to put here.
});
Run Code Online (Sandbox Code Playgroud)

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

主要思想是按预期mouseleave工作.

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

在此输入图像描述

Jac*_*ues 7

在这种情况下,blur() 只会使输入文本失去焦点,尽管它看起来文本不再被选中,但它仍然被选中。要真正取消选择任何文本,您可以执行以下操作:

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