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

时间:2011-05-02 19:07:35

标签: jquery select hover unselect

在我使用.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.
});

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

主要想法是mouseleave也在as expected

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

enter image description here

6 个答案:

答案 0 :(得分:9)

答案 1 :(得分:2)

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

$(this).blur();

答案 2 :(得分: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()

答案 3 :(得分:1)

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

答案 4 :(得分:0)

如果您使用jQuery,您可以尝试使用众多插件中的一个来根据您的需要取消选择或设置插入位置,例如: this one。如果不这样做,由于open-source-licenses

,你仍然可以使用这些插件的纯JavaScript

答案 5 :(得分:0)

在这种情况下,blur()只会使输入文本失去焦点,尽管它使外观看起来不再选择该文本,但仍将其选中。要真正取消选择任何文本,您可以这样做:

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