document和window对象

document.documentElement.scrollTop:滚动条到顶部的距离//适用于标准页面《!doctype》。
document.body.scrollTop:滚动条到顶部的距离//在标准页面下得到为0。
document.body.clientWidth ;document.body.clientHeight.//body对象的宽高。
document.documentElement.clientWidth ;document.documentElement.clientHeight//可视区域的宽高,不包括滚动条。
window.innerHeight;window.innerWidth;//窗口宽高,宽度包含滚动条。

JS获取元素的offsetTop,offsetLeft等属性

obj.clientWidth //获取元素的宽度

obj.clientHeight //元素的高度
obj.offsetLeft //元素相对于父元素的left
obj.offsetTop //元素相对于父元素的top
obj.offsetWidth //元素的宽度
obj.offsetHeight //元素的高度

区别:

clientWidth = width + padding
clientHeight = height + padding
offsetWidth = width + padding + border
offsetHeight = width + padding + border
offset比client多了border的宽度

1
2
3
4
5
6
7
8
9
10
11
12
//获取元素的纵坐标(相对于窗口)
function getTop(e){
  var offset=e.offsetTop;
  if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
  return offset;
}
//获取元素的横坐标(相对于窗口)
function getLeft(e){
  var offset=e.offsetLeft;
  if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);
  return offset;
}

之前也写过一篇JS关于获取元素位置的文章:JS获取元素的offsetTop,offsetLeft等属性,我们可以通过offsetTop和offsetLeft属性获取元素相对窗口的位置,但offsetTop和offsetLeft属性都是相对于父元素定位的,而通常需要获取位置的元素都不是在最外层,所以遍历上级元素的offset相关属性少不了。那效率就成问题了。

1
2
3
4
5
6
7
8
9
10
11
12
//获取元素的纵坐标(相对于窗口)
function getTop(e){
var offset=e.offsetTop;
if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
return offset;
}
//获取元素的横坐标(相对于窗口)
function getLeft(e){
var offset=e.offsetLeft;
if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);
return offset;
}
原文地址:https://www.cnblogs.com/lk1186578324/p/7738253.html