本篇主要介绍如何获取盒子的宽高
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
header{
width: 500px;
margin: 100px auto;
}
div {
width: 200px;
height: 200px;
background-color: brown;
padding: 10px;
border: 4px solid #345678;
margin: 30px;
}
</style>
</head>
<body>
<header>
<div>
查看盒子宽高
</div>
</header>
<script src="./jquery/jquery-1.12.4.min.js"></script>
</body>
- 利用css获取
console.log($('div').css('height'), $('div').css('width'))
这样可以直接获取,但是我们会发现这样获取的尺寸只包含内容盒子的宽高,并且包含单位不利于后期计算,于是我们引入了专门的方法
2. height(),width()方法
console.log($('div').height(), $('div').width())
我们会发现这样获取到了盒子内容的宽高,那么如何获取包含padding,border,margin的宽高呢?
3. innerWidth(),innerHeight()
我们发现这样不仅获得了内容盒子的宽度,还获得了padding的宽度
4. outerWidth(),outerHeight()
上一部我们已经拿到了padding+content的宽度,这一步我们来加上border的宽度
console.log($('div').outerWidth(), $('div').outerHeight());
- outerWidth(true),outerHeight(true);
那么如果要获取padding+content+border+magin的宽度,我们如何获取呢
console.log($('div').outerWidth(true), $('div').outerHeight(true));