如何在jQuery中获得隐藏元素的宽度
一个HTML元素可以在.hide()jQuery函数的帮助下被隐藏,或者我们可以通过在CSS中设置visibility equals hidden来轻松隐藏。我们可以在jQuery中轻松找到这个隐藏元素的宽度。
每个HTML元素都有两种宽度定义,即元素的内宽和外宽。
- innerWidth:当不考虑所选元素的边框宽度时,会考虑这个宽度。
- outerWidth: 这个宽度在考虑选定元素的边框宽度时被考虑。
例子1:这个例子展示了如何计算隐藏元素的innerWidth
<!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").innerWidth();
("#demo").text(demo);
});
});
</script>
<style>
div {
width: 310px;
height: 80px;
font-weight: bold;
color: green;
font-size: 25px;
border: 1px solid green;
visibility: hidden;
border: 2px solid black;
padding: 10px;
}
body {
border: 1px solid black;
padding: 20px;
}
h1 {
color: green;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>
Get the width of the hidden
element in jQuery
</h3>
<div>
</div>
<p id="demo">
Here the width of the
hidden "div" element will appear.
</p>
<button id="btn1">Submit</button>
</center>
</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").outerWidth();
("#demo").text(demo);
});
});
</script>
<style>
div {
width: 310px;
height: 80px;
font-weight: bold;
color: green;
font-size: 25px;
border: 1px solid green;
visibility: hidden;
border: 2px solid black;
padding: 10px;
}
body {
border: 1px solid black;
padding: 20px;
}
h1 {
color: green;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>
Get the width of the hidden
element in jQuery
</h3>
<div>
</div>
<p id="demo">
Here the width of the
hidden "div" element will appear.
</p>
<button id="btn1">Submit</button>
</center>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击按钮后。这里,边界宽度将被添加到结果中。