Home > Article > Web Front-end > Example analysis of the core idea of H5 editor
The code and features are tested under chrome49 and are valid.
The essence of text rendering is the rendering of text nodes. The selected starting point and ending point can be obtained through the browser's built-in object Range
var range = getRangeObject();var start = range.startOffset, end = range.endOffset;var startContainer = range.startContainer;var endContainer = range.endContainer;
The getRangeObjec code is as follows
function getRangeObject(){if(window.getSelection) {var selection = window.getSelection();if(selection.rangeCount > 0) {return selection.getRangeAt(0); } }else if(document.selection) {return document.selection.createRange(); }return null; };
The starting point is always on the left and the ending point is always on the right, regardless of the selection direction.
Only when the beginning of the starting point or the end of the ending point is
, the text node is not returned. The position of the br element can be determined by start and end, respectively startContainer.childNodes [start], endContainer.childNodes[end-1]. The returned text node start represents the starting position of the cursor relative to the starting text node, and end represents the ending position of the cursor relative to the ending text node.
The algorithm to obtain the next text node is
function getNextTextNode(startNode,dir = "nextSibling"){//记录startNode变化之前的状态,startNode变化后无效时便于状态的回滚let unchangeNode = startNode;if(startNode.nodeType == 3){ startNode = startNode[dir]; }while (true){if(startNode == undefined){if(unchangeNode == undefined){//保护机制throw new Error("程序会陷入死循环");break; }/*startNode所在的父元素所有选中节点遍历完毕,将sartNode指向父元素的兄弟节点*/let parent = unchangeNode.parentElement; unchangeNode = parent; startNode = parent[dir]; }else if(startNode.nodeType == 3){//文本节点则退出循环break; }else if(startNode.tagName == "BR"){//处理单标签,避免不必要的迭代unchangeNode = startNode; startNode = startNode[dir]; }else if(startNode.nodeType == 1){/*如果是双标签元素则进入*/unchangeNode = startNode;if(dir == "previousSibling"){ startNode = $(startNode).contents().last().get(0); }else if(dir == "nextSibling"){ startNode = $(startNode).contents().first().get(0); }else {//便于错误的定位throw new Error("错误的遍历方向:"+dir); } }else {//便于错误的定位throw new Error("不期待的元素类型=》"+startNode); } } return startNode; }
//The above function uses external variables + while loop to replace recursion, adding Protection mechanisms reduce misuse and potential bugs leading to extremely poor experience.
Get all text nodes between the start node and the end node
function getTextNodes(startTextNode,endTextNode){ let textNodeArray = []; let node = startTextNode;while (true) { node = getNextTextNode(node);if(node == endTextNode){break; } textNodeArray.push(node); } return textNodeArray; }
The above is the detailed content of Example analysis of the core idea of H5 editor. For more information, please follow other related articles on the PHP Chinese website!