浅谈JavaScript元素的尺寸和位置相关属性

来源:互联网 发布:摄像机ntp端口号 编辑:程序博客网 时间:2024/05/16 16:11

1、offsetWidthoffsetHeight

描述元素外尺寸,元素内容+内边距+边框,不包括外边距和滚动条。

2、clientWidth和clientHeight

描述元素内尺寸,元素内容+内边距,不包括边框(IE下实际包括)、外边距、滚动条。

3、scrollWidth和scrollHeight

元素内容+内边距+溢出尺寸,当内容没有溢出时,scrollWidth和scrollHeight一般分别与clientWidth和clientHeight相等,但实际上不同浏览器有不同处理,它们未必相等。

4、offsetLeft 和offsetTop

描述元素的左上角(边框的外边缘)与已定位的父容器(offsetParent对象——元素最近的定位为relative或absolute的祖先元素,若没有则返回null)左上角的距离。

5、clientLeft 和clientTop

描述内边距的外边缘和边框的外边缘之间的水平和垂直距离,也即左、上边框宽度。

6、scrollLeft和scrollTop

描述元素滚动条的位置,可写。


<!doctype html>  <html>      <head>          <style type="text/css">  #out{width:200px;height:200px;background:red;position:absolute;left:200px;top:1000px;padding:5px;border:5px solid grey;}#in{width:50px;height:50px;position:absolute;left:50px;top:25px;background:blue;padding:5px;border:5px solid grey;}        </style>      </head>      <body>   <div id="out"><div id="in"></div></div><script>var in_div = document.getElementById("in");console.log(in_div.offsetHeight); // 输出:70console.log(in_div.clientHeight); // 输出:60console.log(in_div.scrollHeight); // 输出:60console.log(in_div.offsetTop); // 输出:25console.log(in_div.clientTop); // 输出:5var out_div = document.getElementById("out");console.log(out_div.offsetHeight); // 输出:220console.log(out_div.clientHeight); // 输出:210console.log(out_div.scrollHeight); // 输出:210console.log(out_div.offsetTop); // 输出:1000console.log(out_div.clientTop); // 输出:5document.body.onscroll = function() { // 页面滚动时触发节流函数throttle(scroll, window);}function scroll() {console.log(document.body.scrollLeft);console.log(document.body.scrollTop);}function throttle(method, context) { // 函数节流clearTimeout(method.tId);method.tId = setTimeout(function() {method.call(context);}, 100);}</script>    </body>  </html>

1 0
原创粉丝点击