我试图找出一个特定元素在文档中的距离,理想情况是百分比。
具体来说,我有一个很长的XHTML文档(实际上它是ePub文件的一个组件),我在其中的某个地方有一个<span id="where_am_i">hello</span>
。
如果这是文档中的第一个元素,那么“百分比通过”值将为0.如果它正好在文档的中间,则为50.
它不一定是顶层,它可能嵌套在其他节点中。
我考虑使用像递归$(node).contents().each(function(){...});
之类的东西并计算单词来获取它,不过我想知道这可能是一种缓慢的方法吗?
文档是文本,不太可能包含图像,或文本大小差别很大,所以只需找出文本#where_am_i
的距离就可以了。
提前谢谢!
答案 0 :(得分:1)
您可以使用此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;
}
}
}
答案 1 :(得分:1)
如果您将文档作为字符串,则可以使用indexOf javascript函数
获得非常粗略估计值var html = $('body').html(); // or provided string
var percentage = html.indexOf('where_am_i') / html.length;
var found = percentage >= 0;
答案 2 :(得分:1)
Jquery解决方案:
<div>
<div id="test"></div>
<div></div>
</div>
<div id="result"></div>
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