如何最好地确定元素/节点通过DOM的距离?

我试图找出一个特定元素在文档中的距离,理想情况是百分比。

具体来说,我有一个很长的XHTML文档(实际上它是ePub文件的一个组件),我在其中的某个地方有一个hello

如果这是文档中的第一个元素,则“百分比通过”值将为0.如果它正好在文档的中间,则为50。

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

我考虑使用类似递归的$(node).contents().each(function(){...}); 虽然我想知道这可能是一个缓慢的方法吗?

文档是文本,它不太可能包含图像,或者文本大小#where_am_i很大,所以只需找出文本#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; }); // 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; } } } } } })(); 

仅供参考,您可能也可以使用document.body.getElementsByTagName("*") ,然后遍历nodeList,直到找到您的元素并使用该索引作为衡量您在整个列表中的距离的度量。

 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; } } } 

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

如果您将文档作为字符串,则可以使用indexOf javascript函数进行非常粗略的估计

 var html = $('body').html(); // or provided string var percentage = html.indexOf('where_am_i') / html.length; var found = percentage >= 0; 

Jquery解决方案:

 
var all=$("*").not("script, IFRAME, STYLE, EMBED, OBJECT, head, html,body, meta, title, link"); function getPercentage(el){ return all.index($(el))/all.length*100; } console.log(getPercentage("#test"))//25