本文主要是介绍获取元素宽高和距离定位父级的距离,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
获取元素宽/高和距离定位父级的距离
- 获取元素宽高
offsetWidth/offsetHeight
获取元素的宽度和高度(包含边框和内边距)
clientLeft/clientTop
取元素左/上边框宽度
clientWidth/clientHeight
获取元素宽度(不包含边框)
计算公式:
-
offsetHeight = 元素高度+元素上内边距+元素下内边距+元素上边框+元素下边框
-
offsetWidth = 元素宽度+元素左内边距+元素右内边距+元素左边框+元素右边框
-
clientLeft
= 左边框宽度 -
clientTop
= 上边框宽度 -
clientWidth = 元素高度+元素上内边距+元素下内边距
-
clientHeight= 元素宽度+元素左内边距+元素右内边距
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title></title>
</head>
<style>body{margin: 0px;}.getInfo{width: 200px;height: 220px;background-color: #bae9d9;border: 4px solid pink;margin: 10px 0px 0px 10px;padding: 5px 10px;}
</style>
<body><div class="getInfo"></div>
</body>
<script>let getInfo = document.getElementsByClassName('getInfo')[0]// 228 = 200+10+10+4+4console.log(getInfo.offsetWidth)// 238 = 220+5+5+4+4console.log(getInfo.offsetHeight)// 4console.log(getInfo.clientLeft)// 4console.log(getInfo.clientTop)// 220 = 200+10+10console.log(getInfo.clientWidth )// 230 = 220+5+5console.log(getInfo.clientHeight)
</script>
- 距离定位父级的距离
offsetLeft /offsetTop
距离定位父级的距离计算公式:
offsetLeft = 元素左外边距+父级元素的左内边距
offsetTop= 元素上外边距+父级元素的上内边距
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title></title>
</head>
<style>body{margin: 0px;}.parent {position: relative;width: 500px;height: 500px;border: 1px solid;padding: 20px;}.getInfo{width: 200px;height: 220px;background-color: #bae9d9;border: 4px solid pink;margin: 10px 5px 8px 20px;padding: 5px 10px;}
</style><body><div class="parent"><div class="getInfo"></div></div>
</body>
<script>let getInfo = document.getElementsByClassName('getInfo')[0]// 40 = 20 + 20console.log(getInfo.offsetLeft )// 30 = 10 + 20console.log(getInfo.offsetTop )
</script>
- 获取可视区或者文档的宽高
window.innerWidth
window.innerHeight
document.body.clientWidth
document.body.clientHeight// 1382
console.log(window.innerWidth)
// 1041
console.log(window.innerHeight )
// 1382
console.log(document.body.clientWidth)
// 542
console.log(document.body.clientHeight)
最后用一张图来总结:
这篇关于获取元素宽高和距离定位父级的距离的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!