首页 > 解决方案 > javascript有特异性吗?

问题描述

我在我的html文件中给出了一个div,高度为100x,宽度为100px。我试图使用javascript输出高度,像这样..

console.log(document.GetElementById("box").style.height);
// 我给了 div 一个 box 的 ID 并使用 css 对其进行了样式设置,但它在 console.logged 一个空行。
https://i.stack.imgur.com/zVqEg.png

//但是当我使用css 内联样式设置 div 样式时,它 console.logged 高度。
https://i.stack.imgur.com/biXZK.png

标签: htmlcss

解决方案


style您需要获取#box元素的计算高度,而不是读取属性的值。

有几种方法可以做到这一点。

// includes height + vertical padding
var h = document.getElementById('box').clientHeight;

// includes height + top/bottom padding + top/bottom borders
var h = document.getElementById('box').offsetHeight;

// includes height of the contained document
// (possibly larger than mere height in case of overflow scrolling)
// + top/bottom padding + top/bottom borders
var h = document.getElementById('box').scrollHeight;

还要确保您在开头getElementById()使用小写字母进行调用。g


推荐阅读