如何最好地确定DOM元素/节点有多远? [英] How best to determine how far through the DOM an element/node is?

查看:121
本文介绍了如何最好地确定DOM元素/节点有多远?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



具体来说,我有一个很长的XHTML文档(它是ePub文件的一个组件,实际上),而且我有一个< span id =where_am_i> hello< / span> / p>

如果这是文档中第一个元素,那么percent through值将为0.如果它是文档的中间位置,则为50



它不一定是顶层,它可能嵌套在其他节点中。



我已经考虑过使用像递归 $(node).contents()。each(function(){...} ; 和计数单词得到它,虽然我不知道这可能是一个缓慢的方法吗?



该文档是文本,它不太可能包含图像,或大小不同的文字大小,所以只需找出文本 #where_am_i 是多远。



提前谢谢!

解决方案

您可以使用此treeWalk函数来查找文档中的哪里给定的元素是:



工作演示: http:/ /jsfiddle.net/jfriend00/LGT6x/

  function findElementPercentage(target){
var cnt = 0;
var pos;
treeWalkFast(document.body,function(node){
if(node === target){
pos = cnt;
}
++ cnt;
});
//处理未找到目标的情况
if(pos === undefined){
return undefined;
}
//返回百分比
return(pos / cnt)* 100;


var treeWalkFast =(function(){
//为常量创建闭包
var skipTags = {SCRIPT:true,IFRAME:true ,OBJECT:true,
EMBED:true,STYLE:true,LINK:true,META:true};
return function(parent,fn,allNodes){
var node = parent.firstChild,nextNode;
while(node&& node!= parent){
if(allNodes || node.nodeType === 1){
if(fn(node)=== false){
return(false);
}
}
//如果它是元素&&
//有子&
//有一个标记名&&不在skipTags列表
//中,我们可以枚举子
if(node.nodeType = == 1&& Node.firstChild&&(Node.tagName&& skipTags [node.tagName])){
node = node.firstChild;
} else if(node.nextSibling){
node = node.nextSibling;
} else {
//没有小孩而没有nextsibling
//找到具有nextSibling
的父项((node = node.parentNode)!= parent){
if(node.nextSibling){
node = node.nextSibling;
break;
}
}
}
}
}
})();






FYI,您可能也只需使用 document.body.getElementsByTagName(*),然后遍历nodeList,直到找到您的元素,并将该索引用作衡量整个列表的距离。 / p>

  function findElementPercentage(target){
var all = document.body.getElementsByTagName(*);
(var i = 0; i< all.length; i ++){
if(all [i] === target){
return(i / all.length)* 100;
}
}
}

工作演示: http://jsfiddle.net/jfriend00/AUjq7/


I'm trying to find out how far through a document a specific element is, ideally as a percentage.

Specifically, I have a long XHTML document (it's a component of an ePub file, in fact), and I've got one <span id="where_am_i">hello</span> somewhere within it.

If this was the very first element in the document, the "percentage through" value would be 0. If it was exactly half-way through the document, it would be 50.

It won't necessarily be the top layer, it may be nested within other nodes.

I've considered using something like a recursive $(node).contents().each(function(){...}); and counting words to get to it, though I wonder if that might be a slow way to do it?

The document is text, it's very unlikely to contain images, or massively differing text size, so it's fine to just find out how far through the text #where_am_i is.

Thank you in advance!

解决方案

You can use this treeWalk function to find out where in the document a given element is:

Working demo: http://jsfiddle.net/jfriend00/LGT6x/

function findElementPercentage(target) {
    var cnt = 0;
    var pos;
    treeWalkFast(document.body, function(node) {
        if (node === target) {
            pos = cnt;
        }
        ++cnt;
    });
    // handle situation where target was not found
    if (pos === undefined) {
        return undefined;
    }
    // return percentage
    return (pos / cnt) * 100;
}

var treeWalkFast = (function() {
    // create closure for constants
    var skipTags = {"SCRIPT": true, "IFRAME": true, "OBJECT": true, 
        "EMBED": true, "STYLE": true, "LINK": true, "META": true};
    return function(parent, fn, allNodes) {
        var node = parent.firstChild, nextNode;
        while (node && node != parent) {
            if (allNodes || node.nodeType === 1) {
                if (fn(node) === false) {
                    return(false);
                }
            }
            // if it's an element &&
            //    has children &&
            //    has a tagname && is not in the skipTags list
            //  then, we can enumerate children
            if (node.nodeType === 1 && node.firstChild && !(node.tagName && skipTags[node.tagName])) {
                node = node.firstChild;
            } else  if (node.nextSibling) {
                node = node.nextSibling;
            } else {
                // no child and no nextsibling
                // find parent that has a nextSibling
                while ((node = node.parentNode) != parent) {
                    if (node.nextSibling) {
                        node = node.nextSibling;
                        break;
                    }
                }
            }
        }
    }
})();


FYI, you could probably also just use document.body.getElementsByTagName("*") and then walk through the nodeList until you find your element and use that index as a measure of how far you are through the whole list.

function findElementPercentage(target) {
    var all = document.body.getElementsByTagName("*");
    for (var i = 0; i < all.length; i++) {
        if (all[i] === target) {
            return (i/all.length) * 100;
        }
    }
}

Working demo: http://jsfiddle.net/jfriend00/AUjq7/

这篇关于如何最好地确定DOM元素/节点有多远?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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