【问题标题】:Keep text selection when focus changes焦点改变时保持文本选择
【发布时间】:2014-05-08 21:59:15
【问题描述】:

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

我想将用户的选择保留在文本框中,即使用户专注于灯箱的文本输入。

  1. 在普通文本框中选择文本
  2. 切换灯箱
  3. 专注于灯箱输入

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

谢谢:)

更新

好的,Google 文档使用 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 中的文本选择与灯箱中的输入独立。因此,如果选择了一些文本“这是我的 iframe”,然后切换灯箱并将光标放在输入中,则 iframe 的文本选择会在没有任何 javascript 的情况下持续存在。

我现在正在尝试 Nickolay 的建议。

【问题讨论】:

    标签: javascript textbox focus range selection


    【解决方案1】:

    来自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

    【讨论】:

    • 好吧,我终于进入了这个,但我被 IE 和 FF 困住了。以上是纯 IE - 有人有任何 FF 指针吗?
    • 究竟什么在 Firefox 中不起作用?我不明白为什么第一个 sn-p 不会,只是尝试了第二个,它可以工作......
    • 我的错误——FF执行if,MSIE执行else
    • @Nickolay 我不确定您的解决方案是否有效。请检查此jsfiddle.net/sandeepan_nits/qpZdJ/1 textarea 内的选择在失去焦点时不会持续存在。
    • @Nickolay,可能是我不明白它应该如何工作。即使在焦点消失后,这是否应该能够持续选择?请检查此stackoverflow.com/questions/4484755/…
    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 2011-12-25
    • 2020-03-18
    • 2021-09-09
    • 1970-01-01
    • 2015-11-18
    • 2013-01-14
    • 2016-10-19
    相关资源
    最近更新 更多