2016-05-16 58 views
0

下面的值是我的代码:计算 “左”, “顶”,从固定的位置浮动元素

HTML:

<div id="test"> 
This text is fixed in one spot 
</div> 

CSS:

#test{ 
    border:1px solid black; 
    position: fixed; 
    margin: 8px; 
    right: 0px; 
    bottom: 0px; 
    height: 200px; 
    width: 50%; 
    z-Index: 4; 
} 

到目前为止我能在一个固定的位置制作一个盒子并使其正确显示(高度为200像素,宽度为屏幕的50%)。当屏幕宽度发生变化时,宽度会发生变化,但我的问题是我想计算该框的左上像素位置,因为我不希望框的任何部分出现在任何AdSense广告单元的顶部。屏幕左侧有我的广告单元。

我在JavaScript试图获得这样最左边的像素框的值:

<script> 
alert(document.getElementById('test').left); 
alert(document.getElementById('test').style.left); 
</script> 

而且我没有从任何消息框中的一个数字。我所得到的只是一个空白和“未定义”。

有没有一种方法可以计算盒子的左上角像素位置,而不需要通过JavaScript定时器定期检测值?

不,我不想使用Jquery。

+0

为什么不干脆让广告的高度和位置是高度下面的框中? –

+0

无论用户页面有多远,我都希望该框保留在右下角。 – Mike

回答

1

我认为你在找什么是offsetLeftoffsetTop方法。

alert(document.getElementById('test').offsetLeft); 
 
alert(document.getElementById('test').offsetTop);
#test{ 
 
    border:1px solid black; 
 
    position: fixed; 
 
    margin: 8px; 
 
    right: 0px; 
 
    bottom: 0px; 
 
    height: 200px; 
 
    width: 50%; 
 
    z-Index: 4; 
 
}
<div id="test"> 
 
This text is fixed in one spot 
 
</div>

+0

似乎在这里工作。我希望它适用于所有浏览器。 – Mike