截图效果和盒子模型:
在jQuery中,width()方法用于获得元素宽度;
innerWidth()方法用于获得包括内边界(padding)的元素宽度;
outerWidth()方法用于获得包括内边界(padding)和边框(border)的元素宽度;
如果outerWidth()方法的参数为true则外边界(margin)也会被包括
测试demo代码:
<!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>
<style>
*{
padding:0;
margin:0;
}
body{
background-color: pink;
}
#box{
width:100px;
height:50px;
padding:10px;
border:20px solid blue;
margin:30px;
background-color: purple;
color:white;
}
</style>
</head>
<body>
<div id="box">
我是box的内容,我是box的内容content
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
// 原生js写法
var box = document.getElementById('box');
// 这种写法是错误的,没有该方法
console.log(box.width);//undefined
console.log(box.height);//undefined
// 注意此方法拿到的值带有单位px
console.log(window.getComputedStyle(box).width);//100px
console.log(window.getComputedStyle(box).height);//50px
console.log('offsetWidth为元素width(100)+padding(10*2)+border(20*2)' + box.offsetWidth);//160
console.log('offsetHeight为元素height(50)+padding(10*2)+border(20*2)' + box.offsetHeight);//110
console.log('clientWidth为元素width(100)+padding(10*2)' + box.clientWidth);//120
console.log('clientHeight为元素height(100)+padding(10*2)' + box.clientHeight);//70
/**
*jQuery 写法
*/
var jw = $('#box').width();//100
var jh = $('#box').height();//50
console.log(jw);
console.log(jh);
var jinw = $('#box').innerWidth();//120
var jinh = $('#box').innerHeight();//70
console.log(jinw);
console.log(jinh);
var joutw = $('#box').outerWidth();//160
var jouth = $('#box').outerHeight();//110
// 传入参数true,那么margin (top 和 bottom)也会被包含。
var joutw = $('#box').outerWidth(true);//220
var jouth = $('#box').outerHeight(true);//170
console.log(joutw);
console.log(jouth);
</script>
</body>
</html>