通过JavaScript进行样式化有时才有效



我确定这里有一些潜在的逻辑,我不理解,但无法在网上找到解决方案。有时应用样式,有时不应用样式,尽管没有进行任何更改。当我注释掉一个ID的样式时,另一个ID开始工作,但它们完全独立于彼此,并且在Javascript文档流中切换一个位置使另一个工作?刚接触Javascript几天,这对我来说非常非常奇怪。我在VS code上使用实时服务器。

const result = document.querySelector("#myElement");
result.style.color = "blue";
result.style.backgroundColor = "black";
result.style.fontSize = "80px";
let button = document.getElementById("button");
button.style.color = "red";
let para = document.getElementById("p");
para.style.backgroundColor = "black";
para.style.color = "green";

这里是HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="index.css" type="text/css" />
<title>Document</title>
</head>
<body>
<h1 id="myElement">this is a heading</h1>
<p id="p">this is a pragraph, thanks</p>
<div class="container">
<div class="items-1 item">item 1</div>
<div class="items-2 item">item 2</div>
<div class="items-3 item">item 3</div>
<div class="items-4 item">item 4</div>
<div class="items-5 item">item 5</div>
</div>
<button id="btn">click me</button>
<script src="index.js"></script>
</body>
</html>

您需要根据元素的ID调用元素,根据标签的TagName调用标签,等等,参见下面的注释和更正的代码。

const result = document.getElementById("#myElement"); // you get an element by it's ID //
result.style.color = "blue";
result.style.backgroundColor = "black";
result.style.fontSize = "80px";
let button = document.getElementByTagName("button"); // you get a tag by it's TagName //
button.style.color = "red";
let para = document.getElementByTagName("p"); // you get a tag by it's TagName //
para.style.backgroundColor = "black";
para.style.color = "green";

首先,您应该知道一个ID只能被一个HTML元素占用。。它是唯一的,否则当你做getElementById的时候就会混乱。如果您想引用一个特定的元素,您可以使用querySelector作为单个元素,querySelectorAll作为多个元素,通过使用各自的选择器:

  1. #按Id引用元素。
  2. .按类引用元素。
  3. 直接通过HTML标签引用元素的名称。
  4. 例如:

// Set all divs to have 300x150 and the border
document.querySelectorAll('div').forEach(e => {
e.style.width = '300px';
e.style.height = '150px';
e.style.border = '1px solid #000';
});
// Set style specifically for one element
document.querySelector('#div_1').style.background = '#e8e8e8';
// Making all elements with class elem to have font family: serif
document.querySelectorAll('.elem').forEach(e => {
e.style.fontFamily = 'serif';
});
<p class="elem">Lorem Ipsum</p>
<div class="elem" id="div_1">This is div 1</div>
<div class="elem" id="div_2">This is div 2</div>

注:请注意,querySelectorAll不能用于引用多个元素。

相关内容