JavaScript - 创建自定义元素并应用标准样式

JavaScript - Create an custom element and apply standard styles

我正在创建带有自定义元素的 JavaScript 代码,但我不知道我必须如何设置元素的标准样式。我正在尝试这个:

switchElement.style.backgroundColor = "#555";

但是当我更改 css 样式表时,这将不起作用。有没有办法将标准样式设置为background-color: green?喜欢:

stylesheet.css

background-color: blue; /*didn't make it blue*/

html.html

<switch></switch> <!--This element is custom created by JavaScript-->

如果您的 "switchElemet" 变量正在选择正确的元素,那么它应该可以工作。

检查您的变量这是一个元素还是 null 。试试 console.log(switchElemet).

如果你想让 JS 文件中的 CSS 规则比 CSS 文件中的 CSS 规则更重要,那么你应该添加 <script> 标签在你的 <style><link> 标签之后,像这样:

<!DOCTYPE html>
<html>
<head>
<title>Anything You Like</title>
</head>
<body>
<div id = "switchElement"></div>
<style>
#switchElement{
background-color : red;
}
</style>
<script>
var switchElement = document.getElementById("switch element");
switchElement.style.backgroundColor = "blue";
</script>
</body>
</html>

This will make the switchElement appear blue in color instead of red.