The text node that invokes the splitText method has a nodeValue equal to the substring of the value, from zero to iIndex. The new text node has a nodeValue of the substring of the original value, from the specified index to the value length. Text node integrity is not preserved when the document is saved or persisted.
if (so===0) { // At the start of text sc.parentNode.insertBefore(node, sc); } else if (so >= sc.nodeValue.length) { // At the end of text if (ns) { sc.parentNode.insertBefore(node, sc.nextSibling); } else { sc.parentNode.appendChild(node); } } else { // Middle, need to split // http://msdn.microsoft.com/zh-cn/library/ms536764.aspx nn = sc.splitText(so); sc.parentNode.insertBefore(node, nn); }
第二种情形:startContainer 节点为非 第一种情形中的节点。“偏移是 Range 中的第一个节点在其父节点中的索引”。获取 startContainer 中子节点偏移量为 startOffset 的节点 cn = sc.childNodes[so];,如果存在,则按照 insertNode 方法的定义,应将 node 插入到该节点之前 sc.insertBefore(node, cn);,如果不存在,即 startOffset 大于等于 sc.childNodes.length,则应将 node 插入到 startContainer 的子节点最后sc.appendChild(node);。
if (sc.childNodes.length > 0) { cn = sc.childNodes[so]; }
if (cn) { sc.insertBefore(node, cn); } else { sc.appendChild(node); }
详细代码实现如下:
zRange.prototype.insertNode = function(node) { var sc = this.startContainer, so = this.startOffset, p = sc.parentNode, ns = sc.nextSibling, nn, cn;
// 如果节点是 TEXT_NODE 或者 CDATA_SECTION_NODE if ((sc.nodeType === 3 || sc.nodeType === 4 || sc.nodeType === 8 ) && sc.nodeValue) { if (so === 0) { // At the start of text p.insertBefore(node, sc); } else if (so >= sc.nodeValue.length) { // At the end of text if (ns) { p.insertBefore(node, ns); } else { p.appendChild(node); } } else { // Middle, need to split // http://msdn.microsoft.com/zh-cn/library/ms536764.aspx nn = sc.splitText(so); p.insertBefore(node, nn); } } else { if (sc.childNodes.length > 0) { cn = sc.childNodes[so]; }
if (cn) { sc.insertBefore(node, cn); } else { sc.appendChild(node); } } }
剩下的方法,大家可以尝试着去模拟一把,其实并不复杂,也许会其乐无穷,呵呵。
本文链接:http://www.blueidea.com/tech/program/2010/8131.asp
出处:怿飞's blog
责任编辑:bluehearts
上一页 模拟实现Range的insertNode()方法 [2] 下一页
◎进入论坛网络编程版块参加讨论
|