Javascript 获取循环中引用的子节点的水平偏移位置

Javascript 获取循环中引用的子节点的水平偏移位置,javascript,parent,children,Javascript,Parent,Children,使用普通JavaScript,我试图在循环遍历集合时获取给定子节点的偏移量 我有一个包含一系列文本子节点的容器: var theChildren = document.getElementById( "parentContainer" ).childNodes, theChildrenLen = theChildren.length; for( var i=0; i<theChildrenLen; i++ ) { console.log( theChildren[i].

使用普通JavaScript,我试图在循环遍历集合时获取给定子节点的偏移量

我有一个包含一系列文本子节点的容器:

var theChildren = document.getElementById( "parentContainer" ).childNodes,
    theChildrenLen = theChildren.length;

for( var i=0; i<theChildrenLen; i++ ) {

    console.log( theChildren[i].offsetLeft );

}
var theChildren=document.getElementById(“parentContainer”).childNodes,
theChildrenLen=theChildren.length;

对于(var i=0;i而言,简短的回答是,每个子节点之间都有一个文本节点。如果您console.log'theChildrenLen'变量,您将看到它不是您所期望的。为了过滤掉这些子节点,您应该添加一个If语句,如下所示:

for( var i=0; i<theChildrenLen; i++ ) {
if (theChildren[i].nodeType !== 3)
   console.log( theChildren[i].offsetLeft );
}

for(var i=0;这正是我拥有的大部分内容,因此文本节点不会返回偏移量值?如果我返回整个集合,我将得到一个数组,即
[“t”、“e”、“s”、“t”]
我刚刚验证了TextNode没有用于测量视口定位的扩展。将必须使用另一种解决方案,并可能在每个TextNode周围注入一个跨度以获取偏移量。