lastChild的getBoundingClientRect()。x

时间:2015-04-30 13:21:16

标签: javascript html css getboundingclientrect

我当前的代码完美运行:

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>
    &nbsp;
</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/

2 个答案:

答案 0 :(得分:4)

第一个问题:lastChild返回任何节点,而不仅仅是HTML标记元素。 #center的最后一个孩子是Text个节点(包含&nbsp;),而不是Element,因此它没有getBoundingClientRect方法。您可以像这样选择#c

document.querySelector('#center > *:last-child')

第二个问题:getBoundingClientRect的结果没有x字段。您可以改为使用left

document.querySelector('#center > *:last-child').getBoundingClientRect().left

http://jsfiddle.net/3m2n9otr/2/

答案 1 :(得分:4)

要获取最后一个子元素,您应该使用lastElementChild并获取BoundingClientRect的x位置获取左侧属性,如:

var xLastChild = document.getElementById('center').lastElementChild.getBoundingClientRect().left;

http://jsfiddle.net/Pik_at/3m2n9otr/5/

相关问题