在前面我们已经讲过如何使用jquery来设置css样式,与原生js的语法同理,使用相同的命令,只要不写参数就是取。
语法如下:
- $('#btn').height();//取出不包括内边距和边框的元素尺寸
- $('#btn').innerHeight();//取出包括内边距的元素尺寸
- $('#btn').outerHeight();//取出包括内边距和边框的元素尺寸
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./jquery.js"></script>
<title>Jquery中取元素的尺寸 height innerHeight outerHeight</title>
</head>
<style>
*{
margin:0px;
padding:0px;
}
#pr{
position: relative;
height: 400px;
width: 400px;
background-color: aqua;
margin-top: 300px;
margin-left: 100px;
}
#box{
height: 200px;
width: 200px;
background-color: antiquewhite;
margin-left: 100px;
margin-top: 0px;
border: 5px red solid;
padding: 10px;
}
</style>
<body>
<div id="pr">
<div id="box">
</div>
</div>
</body>
<script>
var height = $('#box').height();
console.log(height);
var height = $('#box').innerHeight();
console.log(height);
var height = $('#box').outerHeight();
console.log(height);
</script>
</html>
解释一下:
以上我们定义了一个id为pr的父元素,它的宽度是400px,高度是400px。
在父元素中定义了一个id为box的子元素,宽度为200px,高度为200px,边框为5px,内边距为10px,所以box的最终长框为200+5*2+10*2=230px。
通过height命令取出的高度为200,该尺寸不包含边框和内边距。
通过innerHeight命令取出的高度为220,该尺寸不包含边框,但包含内边距。
通过outerHeight命令取出的高度为230,该尺寸既包含边框又包含内边距。
请大家务必认真理解以上命令,否则在使用时必将乱套。
|