获取元素宽高和距离定位父级的距离

获取元素宽/高和距离定位父级的距离

  1. 获取元素宽高

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+4
    console.log(getInfo.offsetWidth)
    // 238 = 220+5+5+4+4
    console.log(getInfo.offsetHeight)
	// 4
    console.log(getInfo.clientLeft)
	// 4
    console.log(getInfo.clientTop)
	// 220 = 200+10+10
    console.log(getInfo.clientWidth )
	// 230 = 220+5+5
    console.log(getInfo.clientHeight)
</script>
  1. 距离定位父级的距离

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 + 20
    console.log(getInfo.offsetLeft )
	// 30 = 10 + 20
    console.log(getInfo.offsetTop )
</script>
  1. 获取可视区或者文档的宽高
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)

最后用一张图来总结:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/YMX2020/article/details/106795704
今日推荐