[英]How to keep the selection in a div when I focus in another element in the page?
我正在使用文本編輯器,並且@TimDown的rangy lib發揮了很大作用,但是當我選擇一些文本並專注於文本輸入以在其上編寫鏈接時, 此鏈接將在以后應用於選擇 ,我丟失了選擇,並且選擇變為未選擇!
您可以將選擇保存在以下變量中:
var sel = window.getSelection().getRangeAt(0); //get cursor position
sel = [[sel.startContainer,sel.startOffset],
[sel.endContainer,sel.endOffset]
]; //save cursor position (start and end);
/*Do whatever, let the user change selected element*/
現在,當您在變量中進行選擇時,您可以做任何您想做的事情。 但是選擇中涉及的節點不得更改,否則選擇將指向無效范圍。
現在,您可以再次選擇文本:
var range = document.createRange(); //Creade range object. This is not IE compatible!
range.setStart(sel[0][0], sel[0][1]); //Load start from our variable
range.setEnd(sel[1][0], sel[1][1]); //Load end too
var s = window.getSelection();
s.removeAllRanges(); //I'm not sure this is necessary
s.addRange(range);
然后,您可以獲取文本:
alert("Selected: "+s.toString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.