Keep text selection when focus changes

前端 未结 1 1434
温柔的废话
温柔的废话 2020-12-10 19:42

I have a normal textbox, and a lightbox with a text input.

I want to keep the user\'s selection in the textbox, even when the user focuses on the lightbox\'s text in

1条回答
  •  时光说笑
    2020-12-10 20:09

    From How to preserve text selection when opening a jQuery dialog: you have to preserve selection on blur and restore it on focus:

    $("dialog").focus(function() {
      // save the selection
    }).blur(function() {
      // set the text selection
    });
    

    Setting selection (from jQuery Set Cursor Position in Text Area):

    $.fn.selectRange = function(start, end) {
      return this.each(function() {
        if(this.setSelectionRange) {
          this.focus();
          this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
          var range = this.createTextRange();
          range.collapse(true);
          range.moveEnd('character', end);
          range.moveStart('character', start);
          range.select();
        }
      });
    };
    $('#elem').selectRange(3,5);
    

    Getting selection: http://laboratorium.0xab.cd/jquery/fieldselection/0.1.0/test.html

    0 讨论(0)
提交回复
热议问题