关于如何不使用jQuery获得div的高度有什么想法吗?

我在Stack Overflow中搜索这个问题,似乎每个答案都指向jQuery的.height()。

我尝试了myDiv.style。但是它没有返回任何东西,即使我的div在CSS中设置了它的宽度和高度。


当前回答

var clientHeight = document.getElementById('myDiv').clientHeight;

or

var offsetHeight = document.getElementById('myDiv').offsetHeight;

clientHeight包含填充。

offsetHeight包括填充,滚动条和边界。

其他回答

var clientHeight = document.getElementById('myDiv').clientHeight;

or

var offsetHeight = document.getElementById('myDiv').offsetHeight;

clientHeight包含填充。

offsetHeight包括填充,滚动条和边界。

HTMLElement。返回已定义的元素样式 clientHeight -高度+填充 offsetHeight -高度+填充+边框 scrollHeight -返回高度+填充 getBoundingClientRect() -返回左,上,右,下,x, y, 宽度和高度属性 getComputedStyle() -返回元素的所有CSS属性

// returns defined Style of element const styleHeight = document.getElementById('myDiv').style.height; console.log('style Height : ', styleHeight); // height + padding const clientHeight = document.getElementById('myDiv').clientHeight; console.log('client Height : ', clientHeight); // height + padding + borders const offsetHeight = document.getElementById('myDiv').offsetHeight; console.log('offset Height : ', offsetHeight); // height + padding const scrollHeight = document.getElementById('myDiv').scrollHeight; console.log('scroll Height : ', scrollHeight); // return left, top, right, bottom, x, y, width, and height properties const getBoundingClientRectHeight = document.getElementById('myDiv').getBoundingClientRect().height; console.log('get Bounding Client Rect Height : ', getBoundingClientRectHeight); // returns all CSS properties of an element const styleElementHeight = getComputedStyle(document.getElementById("myDiv")).height; console.log('style Element Height : ', styleElementHeight); <div id="myDiv" style="margin:10px;padding:20px;height:200px;"> <input type="Text"> <input type="button" value="submit"> </div>

一种选择是

const styleElement = getComputedStyle(document.getElementById("myDiv"));
console.log(styleElement.height);
<div id="item">show taille height</div>
<script>
    alert(document.getElementById('item').offsetHeight);
</script>

杰斯菲德尔

js小提琴

var element = document.getElementById('element');
alert(element.offsetHeight);