本文翻译自:Get div height with plain JavaScript
Any ideas on how to get a div's height without using jQuery? 关于如何在不使用jQuery的情况下获得div高度的任何想法?
I was searching Stack Overflow for this question and it seems like every answer is pointing to jQuery's .height() . 我正在搜索Stack Overflow这个问题,似乎每个答案都指向jQuery的.height() 。
I tried something like myDiv.style.height , but it returned nothing, even when my div had its width and height set in CSS. 我尝试了类似myDiv.style.height ,但是即使我的div在CSS中设置了width和height ,它也没有返回任何内容。
#1楼
参考:https://stackoom.com/question/13wjK/使用普通JavaScript获取div高度
#2楼
var element = document.getElementById('element');
alert(element.offsetHeight);
#3楼
var myDiv = document.getElementById('myDiv'); //get #myDiv
alert(myDiv.clientHeight);
clientHeight and clientWidth are what you are looking for. clientHeight和clientWidth是您要寻找的。
offsetHeight and offsetWidth also return the height and width but it includes the border and scrollbar. offsetHeight和offsetWidth还会返回高度和宽度,但它包括边框和滚动条。 Depending on the situation, you can use one or the other. 根据情况,可以使用其中一种。
Hope this helps. 希望这可以帮助。
#4楼
var clientHeight = document.getElementById('myDiv').clientHeight;
or 要么
var offsetHeight = document.getElementById('myDiv').offsetHeight;
clientHeight includes padding. clientHeight包括填充。
offsetHeight includes padding, scrollBar and borders. offsetHeight包括填充,scrollBar和边框。
#5楼
The other answers weren't working for me. 其他答案对我不起作用。 Here's what I found at w3schools , assuming the div has a height and/or width set. 这是我在w3schools上发现的,假设div设置了height和/或width 。
All you need is height and width to exclude padding. 您只需要height和width即可排除填充。
var height = document.getElementById('myDiv').style.height;
var width = document.getElementById('myDiv').style.width;
You downvoters: This answer has helped at least 5 people, judging by the upvotes I've received. 您的投票失败者:根据我收到的投票结果,此答案至少帮助了5个人。 If you don't like it, tell me why so I can fix it. 如果您不喜欢它,请告诉我原因,以便我进行修复。 That's my biggest pet peeve with downvotes; 那是我最大的宠爱之情。 you rarely tell me why you downvote it. 你很少告诉我为什么要投票。
#6楼
<div id="item">show taille height</div>
<script>
alert(document.getElementById('item').offsetHeight);
</script>
1202

被折叠的 条评论
为什么被折叠?



