如何使用javascript将节点置于一个范围内? [英] How to get nodes lying inside a range with javascript?

查看:98
本文介绍了如何使用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*/;

我一直在想过最后几个小时的一种方式,并提出: / p>

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.

MDC / DOM / range

推荐答案

如果递归方法的父节点,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, endNode));

这篇关于如何使用javascript将节点置于一个范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆