lastChild 的 getBoundingClientRect().x
getBoundingClientRect().x of lastChild
我当前的代码完美运行:
CSS:
#center
{
background:#781111;
color:#fff;
position:absolute;
left:50%;
margin-left:-50px;
width:100px;
}
#c
{
position:absolute;
right:0;
background:yellow;
color:#781111;
width:10px;
}
HTML:
<div id="center">
<div id="a">a</div>
<div id="a">b</div>
<div id="c">c</div>
</div>
Javascript:
alert(document.getElementById('center').getBoundingClientRect().x);
现在,到目前为止一切正常,但是当我尝试像这样获取 lastChild (div#c) 时:
alert(document.getElementById('center').lastChild.getBoundingClientRect().x);
无法正常工作。
这是我的 jsFiddle:
http://jsfiddle.net/hezi_gangina/3m2n9otr/
第一期:lastChild
returns 任何节点,不仅仅是 HTML 标记元素。 #center
的最后一个子节点是 Text
节点(包含
),而不是 Element
,因此它没有 getBoundingClientRect
方法。你可以 select #c
像这样:
document.querySelector('#center > *:last-child')
第二个问题:getBoundingClientRect
的结果没有x
字段。您可以使用 left
代替:
document.querySelector('#center > *:last-child').getBoundingClientRect().left
要获取最后一个子元素,您应该使用 lastElementChild 并获取 BoundingClientRect 的 x 位置向左 属性 如:
var xLastChild = document.getElementById('center').lastElementChild.getBoundingClientRect().left;
我当前的代码完美运行:
CSS:
#center
{
background:#781111;
color:#fff;
position:absolute;
left:50%;
margin-left:-50px;
width:100px;
}
#c
{
position:absolute;
right:0;
background:yellow;
color:#781111;
width:10px;
}
HTML:
<div id="center">
<div id="a">a</div>
<div id="a">b</div>
<div id="c">c</div>
</div>
Javascript:
alert(document.getElementById('center').getBoundingClientRect().x);
现在,到目前为止一切正常,但是当我尝试像这样获取 lastChild (div#c) 时:
alert(document.getElementById('center').lastChild.getBoundingClientRect().x);
无法正常工作。
这是我的 jsFiddle: http://jsfiddle.net/hezi_gangina/3m2n9otr/
第一期:lastChild
returns 任何节点,不仅仅是 HTML 标记元素。 #center
的最后一个子节点是 Text
节点(包含
),而不是 Element
,因此它没有 getBoundingClientRect
方法。你可以 select #c
像这样:
document.querySelector('#center > *:last-child')
第二个问题:getBoundingClientRect
的结果没有x
字段。您可以使用 left
代替:
document.querySelector('#center > *:last-child').getBoundingClientRect().left
要获取最后一个子元素,您应该使用 lastElementChild 并获取 BoundingClientRect 的 x 位置向左 属性 如:
var xLastChild = document.getElementById('center').lastElementChild.getBoundingClientRect().left;