注:以下內容只適用于chrome
頁面寬高:
document.body.clientWidth/Height(不包括margin)
document.body.offsetWidth/Height(不包括margin)
document.body.scrollWidth/Height(包括margin)
tips:
1.如果不是最大化瀏覽器窗口,且在body標簽設置min-width,document.body.offsetWidth會比document.body.clientWidth多出2px,那就是滾動條旁邊的2px空白空間。
2.有時候,沒設置overflow:hidden;圖片會撐出頁面寬度。從而,你認為有橫向滾動條的頁面寬度數值不準。
窗口viewport寬高:
window.innerWidth/Height(帶滾動條)
document.documentElement.clientWidth/Height(不帶滾動條)
元素寬高:
element.offsetWidth/Height(width+padding+border)
element.scrollWidth/Height(width+padding,沒加border)
元素位置:
element.offsetTop/Left(相對于父元素offsetParent對象)
通過遞歸父元素,獲取父元素的offsetTop/Left即可獲取元素相對于頁面的位置
function getElementTop(element){
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop += current.offsetTop;
current = current.offsetParent;
}
return actualTop;
}
另一種方法,
使用getBoundingClientRect()方法獲取元素相對于窗口的距離,返回的是left、right、top、bottom,width和height
var X= this.getBoundingClientRect().left+document.body.scrollLeft;
var Y =this.getBoundingClientRect().top+document.body.scrollTop;
頁面滾動距離:
window.pageXOffset/window.pageYOffset
document.body.scrollTop/document.body.scrollLeft
參考鏈接:
http://www.cnblogs.com/dolphinX/archive/2012/11/19/2777756.html
http://www.ruanyifeng.com/blog/2009/09/find_element_s_position_using_javascript.html
http://blog.jobbole.com/44319/
文章列表