代码之家  ›  专栏  ›  技术社区  ›  nfm

焦点更改时保留文本选择

  •  4
  • nfm  · 技术社区  · 16 年前

    我有一个普通的文本框和一个带有文本输入的lightbox。

    我希望在文本框中保留用户的选择,即使用户关注lightbox的文本输入。

    1. 在普通文本框中选择文本
    2. 开关灯箱

    在步骤3,用户的文本选择被丢弃。如何防止这种情况?例如,请参见谷歌文档链接插入灯箱。

    谢谢:)

    好的,所以谷歌文档使用空白页面部分的IFRAME,这是他们处理多个选择的方式。类似这样的内容(请原谅讨厌的HTML):

    // test.html
    <html><body>
      <h1 onclick='lightbox();'>This is the main section</h1>
      <iframe src='frame.html'></iframe>
      <div id='lightbox' style='display: none; position: fixed; top: 0; left: 0; height: 100%; width: 100%; opacity: 0.8; background-color: black;'>
        <input type='text' name='url' />
      </div>
      <script type='text/javascript'>
        function lightbox() {
          document.getElementById('lightbox').style.display = 'block';
        }
      </script>
    </body></html>
    
    // frame.html
    <p>This is my iframe</p>
    

    iframe中的文本选择是 将焦点集中在lightbox中的输入上。因此,如果选择了一些文本“This is my iframe”,则会切换lightbox并将光标放置在输入中,iframe的文本选择将保持不变,而不使用任何javascript。

    我现在正在尝试尼科莱的建议。

    1 回复  |  直到 12 年前
        1
  •  6
  •   Community Mohan Dere    9 年前

    从…起 How to preserve text selection when opening a jQuery dialog :您必须在模糊时保留选择并在聚焦时恢复选择:

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

    设置选择(从 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);
    

    获取选择: http://laboratorium.0xab.cd/jquery/fieldselection/0.1.0/test.html