国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

js getBoundingClientRect() 來獲取頁面元素的位置

2019-11-21 00:05:09
字體:
來源:轉載
供稿:網友
document.documentElement.getBoundingClientRect

下面這是MSDN的解釋:

Syntax

oRect = object.getBoundingClientRect()

Return Value

Returns a TextRectangle object. Each rectangle has four integer properties (top, left, right, and bottom) that represent a coordinate of the rectangle, in pixels.

Remarks

This method retrieves an object that exposes the left, top, right, and bottom coordinates of the union of rectangles relative to the client's upper-left corner. In Microsoft Internet Explorer 5, the window's upper-left is at 2,2 (pixels) with respect to the true client.


 

還是實際解釋下,該方法獲得頁面中某個元素的左,上,右和下分別相對瀏覽器視窗的位置。也不好理解,下面用圖說明下。

該方法已經不再是IE Only了,FF3.0+和Opera9.5+已經支持了該方法,可以說在獲得頁面元素位置上效率能有很大的提高,在以前版本的Opera和Firefox中必須通過循環來獲得元素在頁面中的絕對位置。

 

 

 

下面的代碼舉了個簡單的例子,可以滾動滾動條之后點紅色區域看各個值的變化。

復制代碼 代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
</head>

<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>

有了這個方法,獲取頁面元素的位置就簡單多了,

var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;
var Y =this.getBoundingClientRect().top+document.documentElement.scrollTop;

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 溆浦县| 土默特左旗| 墨脱县| 荔浦县| 炎陵县| 林西县| 安平县| 富宁县| 布尔津县| 中宁县| 靖江市| 舒兰市| 伊金霍洛旗| 泰宁县| 宜昌市| 澄迈县| 河池市| 东城区| 峨山| 宿迁市| 襄城县| 山东省| 隆化县| 成安县| 嵩明县| 大悟县| 九台市| 甘孜| 武宣县| 呼伦贝尔市| 昌江| 满城县| 达州市| 荔波县| 宜章县| 吉林省| 大洼县| 寻甸| 康乐县| 康乐县| 新兴县|