开发者

How do I persist the user selection of a text input when focus is lost and regained in IE?

开发者 https://www.devze.com 2023-03-19 02:47 出处:网络
PROBLEM In Chrome/Firefox, the user\'s selection is returned perfectly, even when the field is out of focus. In IE, the selection is set to 0 when a field is out of focus.

PROBLEM

In Chrome/Firefox, the user's selection is returned perfectly, even when the field is out of focus. In IE, the selection is set to 0 when a field is out of focus.

CODE

I'm currently using jQuery.caret() to determine user selection, which uses the following code:

if ( this[0].setSelectionRange ) {
   begin = this[0].selectionStart;
   end = this[0].selectionEnd;
} else if ( document.selection && document.selection.createRange ) {
   var range = document.selection.createRange();
   begin = 0 - range.duplicate().moveStart( 'character', -100000 );
   end = begin + range.text.length;
}
return { begin: begin, end: end };

DETAILS

I'm working on a very complicated autocomplete solution. Selecting a suggestion using the keyboard is fine, since focus is never lost from the text input. Using the mouse, however, blurs the text input and then refocuses it.

The user's selection and caret position are important to how the suggestion is filled into the field.

DISCUSSION

I'd rather not have to save the user's caret position every time they move it (keydown of left, right, up, down arrows, page up/down, backspace, mouse events click, etc) and it seems like there should be an answer that lets me either:

  1. Listen for some event that I can save the caret before the blur happens (onBlur is too late).
  2. Use a different method to determine user selection in IE.

Once again, this issue is only observed in IE. Other browsers h开发者_如何学编程andle this properly.


IE selection works a bit differently. Check out this fiddle: http://jsfiddle.net/KC48j/11/

0

精彩评论

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

关注公众号