javascript中的offsetWidth、clientWidth、innerWidth及相关属性方法

关于js中的offsetWidth、clientWidth、scrollWidth等一系列属性及其方法一直都傻傻分不清,这里就来总结一下这些方法的用法和含义。

注意: 下面元素属性和元素方法都通过 elem.属性 或 elem.方法 的方式使用,window属性通过 window.属性 的方式使用,document属性则通过document调用。

 1 <script>
 2     /*
 3      ****** 元素视图属性
 4      * offsetWidth 水平方向 width + 左右padding + 左右border-width
 5      * offsetHeight 垂直方向 height + 上下padding + 上下border-width
 6      * 
 7      * clientWidth 水平方向 width + 左右padding
 8      * clientHeight 垂直方向 height + 上下padding
 9      * 
10      * offsetTop 获取当前元素到 定位父节点 的top方向的距离
11      * offsetLeft 获取当前元素到 定位父节点 的left方向的距离
12      * 
13      * scrollWidth 元素内容真实的宽度,内容不超出盒子高度时为盒子的clientWidth
14      * scrollHeight 元素内容真实的高度,内容不超出盒子高度时为盒子的clientHeight
15      * 
16      ****** 元素视图属性结束
17      * 
18      ****** Window视图属性(低版本IE浏览器[<IE9]不支持) 【自测包含滚动条,但网络教程都说不包含???】
19      * innerWidth 浏览器窗口可视区宽度(不包括浏览器控制台、菜单栏、工具栏) 
20      * innerHeight 浏览器窗口可视区高度(不包括浏览器控制台、菜单栏、工具栏)
21      * ***** Window视图属性结束
22      * 
23      ****** Document文档视图
24      * (低版本IE的innerWidth、innerHeight的代替方案)
25      * document.documentElement.clientWidth 浏览器窗口可视区宽度(不包括浏览器控制台、菜单栏、工具栏、滚动条)
26      * document.documentElement.clientHeight 浏览器窗口可视区高度(不包括浏览器控制台、菜单栏、工具栏、滚动条)
27      * 
28      * document.documentElement.offsetHeight 获取整个文档的高度(包含body的margin)
29      * document.body.offsetHeight 获取整个文档的高度(不包含body的margin)
30      * 
31      * document.documentElement.scrollTop 返回文档的滚动top方向的距离(当窗口发生滚动时值改变)
32      * document.documentElement.scrollLeft 返回文档的滚动left方向的距离(当窗口发生滚动时值改变)
33      ****** Document文档视图结束
34      * 
35      ****** 元素方法
36      * 1. getBoundingClientRect() 获取元素到body
37      *  bottom: 元素底边(包括border)到可视区最顶部的距离
38      *  left: 元素最左边(不包括border)到可视区最左边的距离
39      *  right: 元素最右边(包括border)到可视区最左边的距离
40      *  top: 元素顶边(不包括border)到可视区最顶部的距离
41      *  height: 元素的offsetHeight
42      *   元素的offsetWidth
43      *  x: 元素左上角的x坐标 
44      *  y: 元素左上角的y坐标 
45      * 
46      * 2. scrollIntoView() 让元素滚动到可视区
47      * 
48      * ***** 元素方法结束
49      * 
50      */
51 </script>

上面属性中,关于 window.innerWidthwindow.innerHeight, 我自己测试的结果值是包含滚动条的,但网上的教程和相关文档都说不包括滚动条,虽然滚动条的宽度不大,对整体影响也不明显,但如果有道友有准确答案的,还请不吝赐教,顺手留个言,谢谢!

转自:https://blog.csdn.net/qq_33036599/article/details/81224346

原文地址:https://www.cnblogs.com/lydiawork/p/13372152.html