首页 > 解决方案 > JavaScript:setAttribute 有效,但 .style 无效

问题描述

注意:在我的项目中使用 setAttribute 没有问题。这只是一个关于为什么某些东西不起作用的问题。

我已经制作了一个基本的.js,.html.css文件。这是每个的代码:

//Load Document
window.onload = () => {
  //get Body Height and Width
  let body = document.body;
  let html = document.documentElement;
  let bH = Math.max(body.offsetHeight, body.scrollHeight, body.clientHeight, html.offsetHeight, html.scrollHeight, html.clientHeight);
  let bW = Math.max(body.offsetWidth, body.scrollWidth, body.clientWidth, html.offsetWidth, html.scrollWidth, html.clientWidth);
  console.log(`Body Height: ${bH}px`);

  //get document elements
  const menu = document.getElementById("getMenu");
  const menuMarginTB = (bH - menu.offsetHeight) / 2;
  //menu.setAttribute("style", "margin:"+menuMarginTB+"px auto;");
  menu.style.margin = `${menuMarginTB}px auto;`;
};
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body,
html {
  height: 100%;
}

.container {
  position: absolute;
  top: 0;
  left: 0;
  background-color: black;
  height: 100%;
  width: 100%;
}

.menu {
  height: 400px;
  width: 600px;
  border: 1px solid white;
}
<!DOCTYPE html>
<html>

<head>
  <title>Random Website</title>
  <link href="./main.css" type="text/css" rel="stylesheet" />
  <script defer src="./main.js" type="text/javascript"></script>
</head>

<body>
  <div id="getContainer" class="container">
    <div id="getMenu" class="menu">

    </div>
  </div>
</body>

</html>

我已经注释掉了,setAttribute因为它有效,但是当我尝试使用.style.margin它时它不起作用。控制台中没有弹出错误(我使用的是谷歌浏览器)。我不知道为什么它不起作用。这是我尝试过的:

  1. 我尝试使用document.onloaddocument.addEventListener("DOMContentLoaded", ...);但这些都失败了。我目前正在使用window.onload,它也不起作用。
  2. 我尝试defer从脚本标签中删除;但是,defer仅假设在解析每个 HTML 元素后运行此脚本(据我所知),我不知道删除或保留它会如何影响.style.margin.
  3. 我尝试将id名称从更改"menu""getMenu"。我认为 id 和 class 使用相同的名称不仅是不好的做法,而且会影响.style.margin工作方式。但是,当我更改它时,它似乎并没有真正帮助。
  4. 我尝试concatenating了字符串而不是interpolating它。我假设模板插值在我使用它时可能不起作用,但字符串连接似乎没有帮助。

[注意:我可能尝试了更多的东西,但我不记得了。]

我认为这个问题扩展到所有.style属性,因为在查看 Google Chrome 的开发工具时,所有属性都是空白的,即使它们是在.css文件中分配的。

证明 1 我已经分配height给,400px但在这里它显示为"". .js在我运行文件的最后一行使用断点运行后,也会发生同样的事情。当我将鼠标悬停在 上时menu.style.margin,它也会导致"". 证明2

我唯一能想到的可能是某些东西没有加载导致这种情况发生,但即使它没有加载,我也不知道如何解决它。非常感谢您对此事的任何帮助。

标签: javascripthtmlcss

解决方案


这实际上是一个非常简单的错误:)

element.style = value仅当value是此 css 属性的有效值时才有效。在您发布的代码中不是:您可能不在字符串中包含分号。


推荐阅读