JS中DOM元素的位置

2021-10-07 02:10:44 字數 1300 閱讀 9978

<

!doctype html>

"en"

>

"utf-8"

>

"viewport" content=

"width=device-width, initial-scale=1.0"

>

document<

/title>

.box

.container

<

/style>

<

/head>

="container"

>

="box"

>

box<

/p>

box<

/p>

box<

/p>

box<

/p>

box<

/p>

box<

/p>

box<

/p>

box<

/p>

box<

/p>

<

/div>

<

/div>

var box = document.

queryselector

('.box'

)// 獲取的是元素加邊框前後的偏移量,也就是左邊框的寬度

// clienttop 就是上邊框的寬度

console.

log(box.clientleft)

// offsetparent指的是最近的有定位屬性的祖先級,如果都沒有定位,得到body

// offsetleft獲取的就是相對於offsetparent的座標

// 如果box有絕對定位的話,那麼offsetleft就和定位座標left的值一樣

console.

log(box.offsetleft)

// console.log(box.scrolltop) // 在這裡直接獲取永遠都是0

// 當滾輪開始滾動的時候來獲取

box.

onscroll

=function()

// 讓滾輪預設在元素底部,可以給scrolltop賦值

// 滾動內容總高度 - 盒子本身高度可以讓滾動條在最底部

box.scrolltop = box.scrollheight - box.clientheight // 讓滾動條在最底部的公式

<

/script>

<

/body>

<

/html>

js獲取dom元素位置函式

element.getboundingclientrect 方法返回元素的大小及其相對於視口的位置。可以獲取 這些屬性除了width和height都是相對於視窗左上角計算的。由於是當前視窗的屬性值,要想獲取相對於整個網頁的左上角定位值,要給top和left屬性加上當前滾動的位置,通過window.s...

DOM尺寸,DOM元素位置

dom尺寸 doctype html en utf 8 viewport content width device width,initial scale 1.0 document title utils.js script box style head box div 以乙個方向為例,每一種都有寬...

JS獲取DOM元素位置與大小

每乙個html元素都有以下屬性 offsetwidth offsetheight offsetleft offsettop clientwidth clientheight scrollwidth scrollheight scrollleft scrolltop screenx screeny o...