使用普通JavaScript获取div高度

本文翻译自: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中设置了widthheight ,它也没有返回任何内容。


#1楼

参考:https://stackoom.com/question/13wjK/使用普通JavaScript获取div高度


#2楼

jsFiddle jsFiddle

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. 您只需要heightwidth即可排除填充。

    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>

Jsfiddle Jsfiddle

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值