所以下面有这段代码,我将其用于将html字符串解析为iframe(richTextField)。该代码正常工作,并且已找到on the first answer by Tim Down。我不太了解。特别是带有range
的部分。
从文档here:
Range接口表示可以
包含节点和部分文本节点。
我假设范围对象将是用户的选择,包括<div>
这样的标签(如果已选择)。
我将Tim的代码更改为JSFiddle,但我很难理解为什么我的2个div相互放置(甚至是一般的代码)。
所以这是我错误理解的代码,如果有人可以纠正我,我将不胜感激:
var html = "<br/>" + "<div style='background:grey;'>1<div/>"+
"<div style='border:2px solid red'>2</div><br/>";
var window = richTextField;
var sel, range;
document.getElementById('richTextField').focus();
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection(); // 1. So here I get it, we get what the cursor selected.
if (sel.getRangeAt && sel.rangeCount) { // 2. This I don't understand even after reading the doc (there are no return type in the doc which makes it hard to understand).
range = sel.getRangeAt(0); // 2.1 First position in the selection ?
range.deleteContents(); // 3. I'm assuming we delete the highlighted area by the user.
var el = richTextField.document.createElement("div"); 4. // So we create a div that we put in the doc tree of the iframe (richtextField).
el.innerHTML = html; 5. // some text in that div, here my text contains another div.
var frag = richTextField.document.createDocumentFragment(), node, lastNode; 6. // I'm usually programming in java and this syntax is unknown to me.
// what are those after the "," comas ?
//createDocumentFragment as the doc says creates a fragment but doesn't push it to the DOM
while ((node = el.firstChild)) { 7. // I'm assuming we go through all the childs of the root of the el node (which itself is the div we created on number 4.
lastNode = frag.appendChild(node); /// we append every node to the fragment created on 7. The fragment is not yet pushed to the dom tree.
}
range.insertNode(frag); //8. Hum here we push the fragment in the dom. But wasn't that what we did already in 4 ?
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
最佳答案
范围边界不是HTML字符串表示形式中的字符偏移量。相反,它是DOM节点内的偏移量。例如,如果节点是文本节点,则边界表示为节点文本内的字符偏移量。如果节点是元素,则表示为边界之前节点的子节点数。例如,在以下HTML中,其范围用|表示边界的范围:
<div id="test">foo|bar<br>|<br></div>
...范围的起始边界位于作为元素的第一个子元素的文本节点中的偏移量3处,而结束边界位于元素中的偏移量2处,因为存在两个子节点(文本节点“ foobar”和一个元素)位于边界之前。您可以通过编程方式创建范围,如下所示:
var range = rangy.createRange(); // document.createRange() if not using Rangy
var div = document.getElementById("test");
range.setStart(div.firstChild, 3);
range.setEnd(div, 2);
参考:How do I create a range object when I know just the character offsets?