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

2022-01-14,,,,

这篇文章主要介绍了javascript中的offsetWidth、clientWidth、innerWidth及相关属性方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

一、clientWidth和clientHeigh 、 clientTop和clientLeft

1,clientWidth的实际宽度
clientWidth = width+左右padding

2,clientHeigh的实际高度
clientHeigh = height + 上下padding 

3,clientTop的实际宽度
clientTop = boder.top(上边框的宽度)

4,clientLeft的实际宽度
clientLeft = boder.left(左边框的宽度)

二、offsetWidth和offsetHight 、 offsetTop和offsetLeft

1,offsetWidth的实际宽度
offsetWidth = width + 左右padding + 左右boder

2,offsetHeith的实际高度
offsetHeith = height + 上下padding + 上下boder

3,offsetTop实际宽度
offsetTop:当前元素 上边框 外边缘 到 最近的已定位父级(offsetParent) 上边框 内边缘的 距离。如果父级都没有定位,则分别是到body 顶部 和左边的距离

4,offsetLeft实际宽度
offsetLeft:当前元素 左边框 外边缘 到 最近的已定位父级(offsetParent) 左边框 内边缘的            距离。如果父级都没有定位,则分别是到body 顶部 和左边的距离

三、scrollWidth和scrollHeight 、 scrollTop和scrollLeft

1,scrollWidth实际宽度
scrollWidth:获取指定标签内容层的真实宽度(可视区域宽度+被隐藏区域宽度)。

2,scrollHeight的实际高度
scrollHeight:获取指定标签内容层的真实高度(可视区域高度+被隐藏区域高度)

3,scrollTop
scrollTop :内容层顶部 到 可视区域顶部的距离。
实例:var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;持续获取高度的方式:

 window.addEventListener('scroll', ()=>{ var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; }); 

4,scrollLeft
scrollLeft:内容层左端 到 可视区域左端的距离.

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

 

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

以上就是javascript中的offsetWidth、clientWidth、innerWidth及相关属性方法的详细内容,更多请关注本站其它相关文章!

《javascript中的offsetWidth、clientWidth、innerWidth及相关属性方法.doc》

下载本文的Word格式文档,以方便收藏与打印。