js获取元素/屏幕宽高
总结如下
1、获取网页可视区域宽高(随着页面的缩放,所获取的值会相应改变)
- 方法一、不包括滚动条的宽高在内
document.documentElement.clientWidth
、document.documentElement.clientHeight
- 方法二、包括滚动条的宽高在内
window.innerWidth
、window.innerHeight
二者在没有滚动条的情况下,所获取的值相等
为什么所获取的高度与浏览器的高度差别较大?
这是因为 浏览器的宽/高 = 网页可视区域的宽/高 + 其它宽/高(比如说:浏览器的tab页区域、网址区域、书签区域等)
2、获取网页整个页面宽高的方法(不随页面的缩放而改变)
document.documentElement.scrollWidth
、document.documentElement.scrollHeight
上述方法是获取,网页正文全文宽高
示例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
*{
margin: 0;
padding: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#box{
width:2000px;
height:1200px;
background: #ddd;
padding:15px;
margin: 50px;
border: 10px solid red;
}
</style>
<body>
<div id="box">
为什么所获取的高度与浏览器的高度差别较大,<br/>这是因为 浏览器的宽/高 = 网页可视区域的宽/高 + 其它宽/高(比如说:浏览器的tab页区域、网址区域、书签区域等)
</div>
</body>
<script>
//以下测试所获取的值是在1920*1080的屏幕上所获得的值
//获取网页可视区域宽高(不包括滚动条)
let screenWidth = document.documentElement.clientWidth;
let screenHeight = document.documentElement.clientHeight;
console.log('浏览器屏幕的宽高(不包括滚动条)');
console.log(screenWidth,screenHeight); //1903 920
//获取网页可视区域宽高(包括滚动条在内)
//在没有滚动条的情况下,window.innerHeight === document.documentElement.clientHeight; 宽度同理
let h = window.innerHeight;
let w = window.innerWidth;
console.log('浏览器屏幕的宽高(包括滚动条)');
console.log(w,h); //1920 937
//网页正文全文宽高(不包括滚动条,边框,但是包括了padding)
let allWidth = document.documentElement.scrollWidth;
let allHeight = document.documentElement.scrollHeight;
console.log('网页正文全文宽高');
console.log(allWidth,allHeight); //2050 1300
//1.scrollLeft:设置或获取位于给定对象左边界与窗口中目前可见内容的最左端之间的距离;
//2.scrollTop:设置或获取位于给定对象最顶端与窗口中目前可见内容的最左端之间的距离;
//3.offsetLeft:设置或获取位于给定对象相对于版面或由offsetParent属性指定的父坐标的计算左侧位置;
//4.offsetTop:设置或获取位于给定对象相对于版面或由offsetParent属性指定的父坐标的计算顶端位置;
</script>
</html>
3、clientWidth、offsetWidth、scrollWidth等区别
clientWidth和clientHeigh 、 clientTop和clientLeft
1,clientWidth的实际宽度
clientWidth = width+左右padding
2,clientHeigh的实际高度
clientHeigh = height + 上下padding
3,clientTop的实际宽度
clientTop = 上边框的宽度
4,clientLeft的实际宽度
clientLeft = 左边框的宽度
offsetWidth和offsetHight 、 offsetTop和offsetLeft
1,offsetWidth的实际宽度
offsetWidth = width + 左右padding + 左右boder + 左右滚动条宽度
2,offsetHeith的实际高度
offsetHeith = height + 上下padding + 上下boder + 上下滚动条高度
3,offsetTop实际宽度
offsetTop:当前元素 上边框外边缘 到 最近的已定位父级元素的上边框 内边缘的距离。
如果父级都没有定位,则分别是到body 顶部 和左边的距离
4,offsetLeft实际宽度
offsetLeft:当前元素 左边框 外边缘 到 最近的已定位父级(offsetParent) 左边框 内边缘的距离。
如果父级都没有定位,则分别是到body 顶部 和左边的距离
scrollWidth和scrollHeight 、 scrollTop和scrollLeft
1,scrollWidth实际宽度
scrollWidth:获取指定标签内容层的真实宽度(可视区域宽度+被隐藏区域宽度)。
2,scrollHeight的实际高度
scrollHeight:获取指定标签内容层的真实高度(可视区域高度+被隐藏区域高度)
3,scrollTop
scrollTop :内容层顶部 到 可视区域顶部的距离。
4,scrollLeft
scrollLeft:内容层左端 到 可视区域左端的距离.