在jQuery中获取隐藏元素的高度
一个HTML元素可以在.hide()jQuery函数的帮助下被隐藏,或者我们可以通过在CSS中设置visibility equals hidden来轻松隐藏。我们可以在jQuery中轻松找到这个隐藏元素的高度。
每个HTML元素都有两种高度定义,即元素的innerHeight和outerHeight。
- innerHeight。当不考虑所选元素的边框宽度时,会考虑这个高度。
- outerHeight。这个高度在考虑选定元素的边框宽度时被考虑。
例子-1:这个例子展示了如何计算隐藏元素的innerHeight。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function() {
("#btn1").click(function() {
var demo = ("div").innerHeight();
("#demo").text(demo);
});
});
</script>
<style>
div {
width: 310px;
height: 80px;
font-weight: bold;
color: green;
font-size: 25px;
border: 1px solid green;
visibility: hidden;
}
body {
border: 1px solid green;
padding: 10px;
width: 300px;
}
</style>
</head>
<body>
<div>
</div>
<p id="demo">
Here the height of the
hidden "div" element will appear.
</p>
<button id="btn1">Submit</button>
</body>
</html>
输出:
点击前:
点击后:
在这里,边框宽度将不会被添加到结果中。
例子-2:这个例子展示了如何计算隐藏元素的外层高度。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function() {
("#btn1").click(function() {
var demo = ("div").outerHeight();
("#demo").text(demo);
});
});
</script>
<style>
div {
width: 310px;
height: 80px;
font-weight: bold;
color: green;
font-size: 25px;
border: 1px solid green;
visibility: hidden;
}
body {
border: 1px solid green;
padding: 10px;
width: 300px;
}
</style>
</head>
<body>
<div>
</div>
<p id="demo">
Here the height of the hidden
"div" element will appear.
</p>
<button id="btn1">Submit</button>
</body>
</html>
输出:
点击前:
点击后:
这里,边界宽度将被添加到结果中。