var extractTextNodes = function(paragraph) {
var nodes = [];
function callback(node) {
if (node.nodeType === Node.TEXT_NODE) {
nodes.push(node);
} else if (node.nodeType === Node.ELEMENT_NODE) {
node.childNodes.forEach(callback);
}
}
paragraph.childNodes.forEach(callback);
return nodes;
};
var findParentParagraph = function(node) {
var parent = node.parentElement;
while (parent) {
if (parent.tagName === "P") {
return parent;
}
parent = parent.parentElement;
}
return null;
};
var areTextNodesSiblings = function(textNode1, textNode2) {
var p = findParentParagraph(textNode1);
if (!p) {
return false;
}
var allTextNodes = extractTextNodes(p);
var index1 = allTextNodes.indexOf(textNode1);
var index2 = allTextNodes.indexOf(textNode2);
if (index2 === -1) {
return false;
}
return (index1 === index2 - 1) || (index1 === index2 + 1);
};
只需areTextNodesSiblings
通过节点调用即可。
小提琴:https ://jsfiddle.net/krmnve37/1/
标题说“视觉上是连续的”,但“EDITED 2. Context”说节点必须在同一段落中。以下函数将检查两个节点是否在同一段落中,而不是它们是否彼此相邻:
var areTextNodesInTheSameParagraph = function(textNode1, textNode2) {
var p = findParentParagraph(textNode1);
if (!p) {
return false;
}
var allTextNodes = extractTextNodes(p);
var index1 = allTextNodes.indexOf(textNode1);
var index2 = allTextNodes.indexOf(textNode2);
return index1 > -1 || index2 > -1;
};