关于如何不使用jQuery获得div的高度有什么想法吗?
我在Stack Overflow中搜索这个问题,似乎每个答案都指向jQuery的.height()。
我尝试了myDiv.style。但是它没有返回任何东西,即使我的div在CSS中设置了它的宽度和高度。
关于如何不使用jQuery获得div的高度有什么想法吗?
我在Stack Overflow中搜索这个问题,似乎每个答案都指向jQuery的.height()。
我尝试了myDiv.style。但是它没有返回任何东西,即使我的div在CSS中设置了它的宽度和高度。
当前回答
<div id="item">show taille height</div>
<script>
alert(document.getElementById('item').offsetHeight);
</script>
杰斯菲德尔
其他回答
var myDiv = document.getElementById('myDiv'); //get #myDiv
alert(myDiv.clientHeight);
clientHeight和clientWidth就是你要找的。
offsetHeight和offsetWidth也返回高度和宽度,但它包括边界和滚动条。根据具体情况,您可以使用其中一种。
希望这能有所帮助。
js小提琴
var element = document.getElementById('element');
alert(element.offsetHeight);
除了el。clientHeight和el。当你需要元素内部内容的高度时(不管元素本身设置的高度),你可以使用el.scrollHeight。更多信息
如果你想将元素高度或max-height设置为内部动态内容的精确高度,这可能很有用。例如:
var el = document.getElementById('myDiv')
el.style.maxHeight = el.scrollHeight+'px'
一种选择是
const styleElement = getComputedStyle(document.getElementById("myDiv"));
console.log(styleElement.height);
<div id="item">show taille height</div>
<script>
alert(document.getElementById('item').offsetHeight);
</script>
杰斯菲德尔