龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > Javascript编程 >

javascript获取页面元素具体位置方法

时间:2012-12-29 08:41来源:未知 作者:admin 点击:
分享到:
记得以前getBoundingClientRect只能在ie下使用,现在可以在FF3+,opera9.5+,safari 4,最初我们只用x += el.offsetLeft;_y += el.offsetTop;}while(el=el.offsetParent);return {x:_x,y:_y};这类代码来解决。 getBoundingClie
记得以前getBoundingClientRect只能在ie下使用,现在可以在FF3+,opera9.5+,safari 4,最初我们只用x += el.offsetLeft;_y += el.offsetTop;}while(el=el.offsetParent);return {x:_x,y:_y};这类代码来解决。

getBoundingClientRect();该方法获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置,他返回的是一个对象,即Object,该对象有是个属性:top,left,right,bottom;这里的top、left和css中的理解很相似,但是right,bottom和css中的理解有点不一样,看示意图:

点击查看原图 点击查看原图   可以滚动滚动条之后点红色区域看各个值的变化:

完整实例代码如下

 代码如下
<body style="width:2000px; height:1000px;">
    <div id="demo" style="position:absolute; left:518px; right:100px; width:500px; height:500px; background:#CC0000; top: 114px;">Demo为了方便就直接用绝对定位的元素</div>
</body>
</html>
<script>
document.getElementById('demo').onclick=function (){
        if (document.documentElement.getBoundingClientRect) {
            alert("left:"+this.getBoundingClientRect().left)
            alert("top:"+this.getBoundingClientRect().top)
            alert("right:"+this.getBoundingClientRect().right)
            alert("bottom:"+this.getBoundingClientRect().bottom)
            var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;
            var Y = this.getBoundingClientRect().top+document.documentElement.scrollTop;
            alert("Demo的位置是X:"+X+";Y:"+Y)
        }
}
</script>

注:getBoundingClientRect()是IE特有的,目前FF3+,opera9.5+,safari 4,都已经支持这个方法。


收藏文章
表情删除后不可恢复,是否删除
取消
确定
图片正在上传,请稍后...
评论内容为空!
还没有评论,快来抢沙发吧!

热评话题

按钮 内容不能为空!
立刻说两句吧! 查看0条评论
精彩图集

赞助商链接