html - 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
解决方案
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
推荐阅读
- memory - 为什么删除 sed 中的一行会占用内存?
- html - 根据另一个元素的宽度定位元素
- javascript - 如何从 Excel 桌面关闭使用 OfficeRuntime.displayWebDialog 创建的对话框?
- reactjs - 如何在 React 中传递参数和 Input 的目标?
- javascript - 是否可以在调用 next 之前等待调用 ofType 运算符中的所有操作?
- javascript - 使用 reactjs 将多个 Base64 解码的 pdf 合并为一个 pdf
- mysql - phpmyadmin 页面未在 xampp 服务器中打开
- docker - 在 0.000 秒内运行 0 次测试
- javascript - 如何只显示一个具有相同类的 div 然后其他
- json - 如果任何嵌套值与设定值匹配,则打印键