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,都已經支援這個方法。