用JS获取CSS样式值时访问元素style属性报null错误如何解决
问题成因
浏览器加载HTML文档时会按从上到下的顺序逐行解析执行:
- 你将
<script src="index.js"></script>放在了<head>标签内,JS代码执行时,<body>内的<div id="square">元素还没有被解析到DOM树中 - 此时
document.getElementById('square')的返回值为null,尝试访问null的style属性就会触发你遇到的TypeError错误
额外说明:就算DOM加载完成后直接调用.style.top也无法拿到外部CSS文件中定义的top值,.style属性只能读取元素行内style属性上绑定的样式。
解决方案
提供3种可任选的修复方案:
- 方案1:调整script标签位置
将JS文件的引入位置挪到</body>闭合标签之前,确保DOM完全解析完成后再执行JS代码,修改后的HTML结构如下:<html> <head> <title>Simple Movement</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="style.css"/> </head> <body> <div id="square"></div> <!-- 移动script到body底部 --> <script src="index.js"></script> </body> </html> - 方案2:给script标签添加defer属性
无需改动script标签位置,添加defer属性后浏览器会自动等待DOM解析完成后再执行JS文件:<script src="index.js" defer></script> - 方案3:JS代码包裹在DOM加载完成事件中
无需修改HTML结构,修改index.js代码,将逻辑放在DOMContentLoaded事件回调内,同时如果需要读取外部CSS定义的样式,使用getComputedStyle方法:document.addEventListener('DOMContentLoaded', function() { const square = document.getElementById('square'); // 读取行内style属性的top值用 square.style.top // 读取外部CSS生效的top值用如下方法 const finalStyle = window.getComputedStyle(square); console.log(finalStyle.top); // 输出 200px })
内容的提问来源于stack exchange,提问作者ali varaste pour
相关产品推荐
相关产品推荐

