2

我当前的代码运行良好:

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/

4

2 回答 2

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/

于 2015-04-30T13:24:56.240 回答
4

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

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

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

于 2015-04-30T13:43:23.657 回答