如何用jQuery获得一个div的高度
在这篇文章中,我们将学习如何使用jQuery获得一个div的高度。在jQuery中,height方法被用来获取HTML中任何元素的高度。height方法设置并返回HTML元素的高度。
方法1: height()方法返回第一个匹配元素的高度,但height(value)方法设置所有匹配元素的高度。
// Returns the height of the first matched element
(selector).height()
// Set the height of the all matched elements(selector).height(value);
因此,在height()方法的帮助下,我们将找到div的高度。
// Returns the height of the first matched div
$("div").height()
示例:
<!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">
<!-- Link of jQuery CDN -->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
</head>
<body>
<!-- div element -->
<div style="color: red;
background-color: black;
margin: 80px 80px;
padding: 40px 400px;">
This is the div.
<p></p>
<button>
Click to see the height of div
</button>
</div>
<script>
// After click btn, it will show
// the height of the div
("button").click(function () {
// Height of the div
var height =("div").height();
// Show the height of the div
$("p").html("height of the div :" + height);
});
</script>
</body>
</html>
输出:
在点击按钮之前:
点击按钮后:
方法2:jQuery使用innerHeight()方法来检查元素的内部高度,包括padding。
语法:
$("param").innerHeight()
示例:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
#demo {
height: 150px;
width: 350px;
padding: 10px;
margin: 3px;
border: 1px solid blue;
background-color: lightgreen;
}
</style>
<script>
(document).ready(function () {
("button").click(function () {
var msg = "";
msg += "Inner Height of div: " + ("#demo").
innerHeight() + "</br>";
("#demo").html(msg);
});
});
</script>
</head>
<body>
<div id="demo"></div>
<button>Click Me!!!</button>
<p>
Click on the button and check
the innerHeight of an element
(includes padding).
</p>
</body>
</html>
输出:
在点击 “点击我 “按钮之前:
点击 “点击我 “按钮后:
方法3:这种方法使用outerHeight()方法来查找指定元素的外部高度。一个元素的外部高度包括padding和border。
语法:
$(selector).outerHeight(includeMargin)
例子:这个例子显示一个元素的外部高度。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Style to create box using
padding and margin -->
<style>
.geeks {
height: 80px;
width: 200px;
padding: 5px;
margin: 5px;
border: 2px solid black;
background-color: green;
text-align: center;
}
</style>
<!-- Script to return outer height -->
<script>
(document).ready(function () {
("button").click(function () {
alert("Outer height of div: "
+ $("div").outerHeight());
});
});
</script>
</head>
<body>
<div class="geeks">
GeeksforGeeks
</div>
<button>
Click Here to display outer height
</button>
</body>
</html>
输出:
在点击按钮之前: