javascript - 如何用js获取样式值
问题描述
所以我有一个简单的 html 文件,它由一个 div 组成;和一个 css 文件,它具有上述 div 的简单样式:
html:
<html>
<head>
<title>Simple Movement</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="index.js"></script>
</head>
<body>
<div id="square"></div>
</body>
</html>
CSS:
body {
margin: 0;
}
#square {
width: 100px;
height: 100px;
border: 1px solid #095057;
background-color: #20979e;
position: absolute;
left: 200px;
top: 200px;
}
在我的 js 文件中,我做了一个简单的日志,如下所示:
console.log(document.getElementById('square').style.top)
但我收到一个错误:
Uncaught TypeError: Cannot read properties of null (reading 'style') at index.js:1
我不知道为什么它说风格是空的。你呢?
解决方案
我不知道为什么它说风格是空的。你呢?
它没有。它说document.getElementById('square')
返回,因此您正在null
读取导致错误的属性。style
null
发生这种情况是因为您的脚本在头部加载(并执行)。此时 DOM 中尚不存在 ID 为“square”的元素。
将您的脚本移动到您的元素下方(参见代码片段)或使用如下标记async defer
:<script src="index.js" async defer></script>
使其在DOM 解析完成后加载并执行。
此外,访问style
只会显示 style 属性中的内联样式,因此不会从样式表文件(或内联样式表)中获取值。
使用computedStyleMap()
(参见https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap)获取包括所有样式表在内的实际计算样式。
body {
margin: 0;
}
#square {
width: 100px;
height: 100px;
border: 1px solid #095057;
background-color: #20979e;
position: absolute;
left: 200px;
top: 200px;
}
<html>
<head>
<title>Simple Movement</title>
<meta charset="UTF-8">
</head>
<body>
<div id="square"></div>
<script>
console.log(document.getElementById('square').computedStyleMap().get('top').value);
</script>
</body>
</html>
推荐阅读
- java - 声纳分析需要詹金斯的太多时间
- plot - 如何使用 Plots.jl 在 Julia 中制作堆积面积/折线图?
- java - 将静态方法添加到枚举 scala
- java - 使用 JSP 模板生成 HTML 文件
- c# - 检查计算机是否处于安全模式 C#
- c# - ASP.NET Core 2 Console.WriteLine 输出未出现在 Docker 日志中
- nginx - 拒绝所有来自特定 IP 的 Nginx 访问
- excel - 如何找到只有空格的空白单元格/单元格
- react-native - React Native 的 Webpack 配置
- python - Python 继续使用 if 或 else