首页 > 解决方案 > 如何用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

我不知道为什么它说风格是空的。你呢?

标签: javascripthtmlcss

解决方案


我不知道为什么它说风格是空的。你呢?

它没有。它说document.getElementById('square')返回,因此您正在null读取导致错误的属性。stylenull

发生这种情况是因为您的脚本在头部加载(并执行)。此时 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>


推荐阅读