雖然@盧卡斯的答案是好的,但有很多缺失,可以讓你成功地使用它。選擇開始的節點必須是確切的節點,而不是父節點。在我們的例子中,我們試圖將一些文本放入TextAngular控件中,然後選擇看起來喜歡____的文本,以便用戶可以「填空」。
我們的投入是爲了<p>Some text goes here: _____</p>
或
<p>Some partial goes here
<ul>
<li>Option 1</li>
<li>_____</li>
</ul>
爲了得到這個工作的HTML,我們不得不在最後寫的東西,找到下劃線在正確的元素
function find_(node) {
var i, n;
// return the node with the _'s
for(i=0; i < node.childNodes.length; ++i) {
n = node.childNodes[i];
console.debug(n);
if(n.textContent) {
console.debug(n, n.textContent);
if(n.textContent.search(/___+/) > 0) {
return n;
}
}
if(n.childNodes) {
console.debug(n, n.childNodes);
n = find_(n);
if(n) {
return n;
}
}
}
return null;
}
所以,找到節點滿足<get the node the selection starts in>
的工作比這個簡單的句子讓我相信的工作要多得多。
在<ul>
的情況。包含____的節點是li節點的firstChild。
我已經把這個在這裏幫助其他需要做到這一點不知道爲什麼他們得到了錯誤信息
IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset 65.
當問題他們只是在尋找錯誤的節點。
謝謝,但我需要能夠跨元素邊界進行選擇。而通過「隨意」,我並不是指* random *。我確切地知道選擇應該開始和結束的元素,直到字符偏移。 – Lucas 2009-11-15 17:38:44