开发者

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

开发者 https://www.devze.com 2023-03-02 13:41 出处:网络
After I use .select() to select the text in the input box when hovered over I did the following: HTML:

After I use .select() to select the text in the input box when hovered over I did the following:

HTML:

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

jQuery开发者_JS百科:

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

    this.select();

}).mouseleave(function() {

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

See here. Warning for it to function correctly (in jsfiddle) you must click once in the result frame.

The main idea is mouseleave is working as as expected also.

As you might have noticed, I can't figure out a way to un-select the text when you hover out and avoid this:

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


use .blur();

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


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();
});


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


The best solution if you did not want to blur your input is:

getSelection().collapseToEnd()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号