簡體   English   中英

焦點更改時保持文本選擇

[英]Keep text selection when focus changes

我有一個普通的文本框和一個帶文本輸入的燈箱。

我希望將用戶的選擇保留在文本框中,即使用戶專注於燈箱的文本輸入也是如此。

  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中的文本選擇與燈箱中輸入的焦點無關 因此,如果選擇了某些文本“This is my iframe”,則會切換燈箱並將光標放在輸入中,iframe的文本選擇會在沒有任何javascript的情況下持續存在。

我現在正在嘗試Nickolay的建議。

如何在打開jQuery對話框時保留文本選擇 :您必須保留模糊選擇並在焦點上恢復它:

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

設置選擇(來自文本區域中的jQuery設置光標位置 ):

$.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM