如何使用javascript获取位于范围内的节点? [英] How to get nodes lying inside a range with javascript?
问题描述
我正在尝试获取范围对象内的所有 DOM 节点,执行此操作的最佳方法是什么?
I'm trying to get all the DOM nodes that are within a range object, what's the best way to do this?
var selection = window.getSelection(); //what the user has selected
var range = selection.getRangeAt(0); //the first range of the selection
var startNode = range.startContainer;
var endNode = range.endContainer;
var allNodes = /*insert magic*/;
过去几个小时我一直在想办法并想出了这个:
I've been been thinking of a way for the last few hours and came up with this:
var getNextNode = function(node, skipChildren){
//if there are child nodes and we didn't come from a child node
if (node.firstChild && !skipChildren) {
return node.firstChild;
}
if (!node.parentNode){
return null;
}
return node.nextSibling
|| getNextNode(node.parentNode, true);
};
var getNodesInRange = function(range){
var startNode = range.startContainer.childNodes[range.startOffset]
|| range.startContainer;//it's a text node
var endNode = range.endContainer.childNodes[range.endOffset]
|| range.endContainer;
if (startNode == endNode && startNode.childNodes.length === 0) {
return [startNode];
};
var nodes = [];
do {
nodes.push(startNode);
}
while ((startNode = getNextNode(startNode))
&& (startNode != endNode));
return nodes;
};
然而,当结束节点是开始节点的父节点时,它返回页面上的所有内容.我确定我忽略了一些明显的东西?或者可能以完全错误的方式进行.
However when the end node is the parent of the start node it returns everything on the page. I'm sure I'm overlooking something obvious? Or maybe going about it in totally the wrong way.
推荐答案
如果 getNextNode 是父节点,它会递归地跳过你想要的 endNode.
The getNextNode will skip your desired endNode recursively if its a parent node.
改为在 getNextNode 内部执行条件中断检查:
Perform the conditional break check inside of the getNextNode instead:
var getNextNode = function(node, skipChildren, endNode){
//if there are child nodes and we didn't come from a child node
if (endNode == node) {
return null;
}
if (node.firstChild && !skipChildren) {
return node.firstChild;
}
if (!node.parentNode){
return null;
}
return node.nextSibling
|| getNextNode(node.parentNode, true, endNode);
};
在while语句中:
while (startNode = getNextNode(startNode, false , endNode));
这篇关于如何使用javascript获取位于范围内的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!