原生js獲取 一個dom元素距離頁面可視區域的位置值getBoundingClientRect();
這個方法返回一個矩形對象,包含四個屬性:left、top、right和bottom。分別表示元素各邊與頁面上邊和左邊的距離。
var box=document.getElementById('box'); // 獲取元素
alert(box.getBoundingClientRect().top); // 元素上邊距離頁面上邊的距離
alert(box.getBoundingClientRect().right); // 元素右邊距離頁面左邊的距離
alert(box.getBoundingClientRect().bottom); // 元素下邊距離頁面上邊的距離
alert(box.getBoundingClientRect().left); // 元素左邊距離頁面左邊的距離
獲取滾動軸的距離
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;