1. 程式人生 > >【面向JS--元素定位】

【面向JS--元素定位】

1、offset系列方法

offset

offset示意圖

offsetHeight示意圖

2、scroll系列方法

scroll

scroll示意圖

scroll示意圖

3、client系列

clientX和clientY     獲取滑鼠在可視區域的位置     
clientWidth = width + padding 元素可見區域寬
clientHeight = height + padding 元素可見區域高
clientLeft,clientTop     邊框的寬度,若有滾動條的話,包括滾動條

client示意圖

client示意圖

4、height 和 width

height 和 width 是獲取元素的樣式中的高度和寬度,在javascript中它是屬於物件的style物件屬性中的一個成員,它的值是一個字元型別的(50px等),而另外三個高度的值是int型別的,它們是物件的屬性。

document.body.height 就會提示undenifine,
必須寫成:document.body.style.height

獲得計算後樣式的方法

w3c標準   window.getComputedStyle(element, "偽類")[屬性]
IE瀏覽器   element.currentStyle[屬性]
封裝瀏覽器相容性函式  
//封裝
function getStyle(element, attr) {
    if(window.getComputedStyle) {
        return window.getComputedStyle(element, null
)[attr]; } else { return element.currentStyle[attr]; } }

doc.getBoundingClientRect() 獲取文件上下左右距離頁面左上角的距離及本身寬高

var ClientRect = document.getElementById("box").getBoundingClientRect();
console.log(ClientRect )

ClientRect {
    bottom: 515
    height: 327
    left: 22
    right: 670
    top: 188
width: 648 }