Unselect what was selected in an input with .select()

本秂侑毒 提交于 2019-11-27 15:36:38

If you are using jQuery, try using blur().

$(this).blur();

This works:

$(".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();

});

There should be a better way to solve it thought.

Edit: of course there's blur().

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

if you use jQuery, you could try one of the many plugins for unselecting or setting the caret position by your needs, e.g. this one. if you don't, you still can use the pure JavaScript of these plugins due to the open-source-licences

In this case, blur() only unfocus from the input text, and although it gives the appearance the text is not selected anymore, it is still selected. To truly unselect any text, you would do:

$(".hoverAble").mouseenter(function() {
    this.select();
}).mouseleave(function() {
    $(this).prop('selectionStart', 0).prop('selectionEnd',0).blur();
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!