javascript - 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
它时它不起作用。控制台中没有弹出错误(我使用的是谷歌浏览器)。我不知道为什么它不起作用。这是我尝试过的:
- 我尝试使用
document.onload
,document.addEventListener("DOMContentLoaded", ...);
但这些都失败了。我目前正在使用window.onload
,它也不起作用。 - 我尝试
defer
从脚本标签中删除;但是,defer
仅假设在解析每个 HTML 元素后运行此脚本(据我所知),我不知道删除或保留它会如何影响.style.margin
. - 我尝试将
id
名称从更改"menu"
为"getMenu"
。我认为 id 和 class 使用相同的名称不仅是不好的做法,而且会影响.style.margin
工作方式。但是,当我更改它时,它似乎并没有真正帮助。 - 我尝试
concatenating
了字符串而不是interpolating
它。我假设模板插值在我使用它时可能不起作用,但字符串连接似乎没有帮助。
[注意:我可能尝试了更多的东西,但我不记得了。]
我认为这个问题扩展到所有.style
属性,因为在查看 Google Chrome 的开发工具时,所有属性都是空白的,即使它们是在.css
文件中分配的。
证明 1
我已经分配height
给,400px
但在这里它显示为""
. .js
在我运行文件的最后一行使用断点运行后,也会发生同样的事情。当我将鼠标悬停在 上时menu.style.margin
,它也会导致""
. 证明2
我唯一能想到的可能是某些东西没有加载导致这种情况发生,但即使它没有加载,我也不知道如何解决它。非常感谢您对此事的任何帮助。
解决方案
这实际上是一个非常简单的错误:)
element.style = value
仅当value
是此 css 属性的有效值时才有效。在您发布的代码中不是:您可能不在字符串中包含分号。
推荐阅读
- angular - 角度自动完成对象,其中对象名称与值不同
- vert.x - vertx 重新部署参数不适用于 exec-maven-plugin
- android - GSON 在 toJson() 中自动排序键
- angular - Angular 10 单元测试 - 组件实例返回未定义
- asp.net - ViewModel 数组显示空值(ASP.Net MVC 5)
- ssl - 使用 Tungstenite 实现 SSL:SSL 警报编号 42
- ios - 有没有办法从 App Store 中排除需要计步器的应用程序?
- r - 删除一行中的重复值
- azure-cosmosdb-gremlinapi - 当您运行简单查询时,您期望的通常 RU 值是多少?
- spring-security - Spring Security,OAUTH2,动态客户端秘密