JavaScript 如何获取div高度
在本文中,我们将看到如何使用JavaScript获取div的高度。有以下几种方法:
- 使用offsetHeight属性。
- 使用clientHeight属性。
- 使用getBoundingClientRect()方法。
方法1:使用offsetHeight属性
元素的offsetHeight属性是一个只读属性,用于以像素为单位返回元素的高度。它包括元素的任何边框或填充。可以使用此属性来查找
元素的高度。
语法:
divElement.offsetHeight
示例: 在这个示例中,我们将使用 offsetHeight属性 。
<style>
.box {
height: 100px;
width: 100px;
background-color: green;
display: inline-block;
}
</style>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Get the height of
<div>
element using JavaScript
</div>
</b>
<p>
Click on the button to get the height
of
element
</p>
<div class="box"></div>
<p>
Height of the div:
<span class="output"></span>
</p>
<button onclick="getHeight()">
Get Height
</button>
<script type="text/javascript">
function getHeight() {
divElement = document.querySelector(".box");
elemHeight = divElement.offsetHeight;
document.querySelector(".output").textContent
= elemHeight + "px";
}
</script>
输出:
如何使用JavaScript获取<div>
的高度?
方法2:使用clientHeight属性
元素的clientHeight属性是一个只读属性,用于以像素为单位返回元素的高度。它仅包括应用于元素的填充,并排除边框、边距或水平滚动条。这个属性可以用来找到div元素的高度。
语法:
divElement.clientHeight
示例: 在这个示例中,我们将使用 clientHeight 属性 。
<!-- HTML elements to iterate -->
<style>
.box {
height: 100px;
width: 100px;
background-color: green;
display: inline-block;
}
</style>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Get the height of
<div>
element using JavaScript
</div>
</b>
<p>
Click on the button to get the height
of
<div>
element
</div>
</p>
<div class="box"></div>
<p>
Height of the div:
<span class="output"></span>
</p>
<button onclick="getHeight()">
Get Height
</button>
<script type="text/javascript">
function getHeight() {
divElement = document.querySelector(".box");
elemHeight = divElement.clientHeight;
document.querySelector(".output").textContent
= elemHeight + "px";
}
</script>
方法3:使用getBoundingClientRect() 方法
getBoundingClientRect() 方法用于返回一个DOMRect对象,该对象包含与边界矩形的尺寸相关的8个属性。DOMRect对象的其中一个属性是height属性,它返回DOMRect对象的高度。可以使用这个属性来查找div元素的高度。
语法:
elemRect = divElement.getBoundingClientRect();
elemHeight = elemRect.height;
示例: 在这个示例中,我们将看到使用 getBoundingClientRect()方法
<style>
.box {
height: 100px;
width: 100px;
background-color: green;
display:inline-block;
}
</style>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Get the height of
<div>
element using JavaScript
</div>
</b>
<p>
Click on the button to get the height
of
<div>
element
</div>
</p>
<div class="box"></div>
<p>
Height of the div:
<span class="output"></span>
</p>
<button onclick="getHeight()">
Get Height
</button>
<script type="text/javascript">
function getHeight() {
divElement = document.querySelector(".box");
elemRect = divElement.getBoundingClientRect();
elemHeight = elemRect.height;
document.querySelector(".output").textContent
= elemHeight + "px";
}
</script>