首页 > 解决方案 > 将类名添加到新创建的 div 并修改样式

问题描述

我正在尝试通过 id 获取 div,并向该 div 添加事件侦听器,在我的情况下,我正在尝试实现一个简单的mouseover事件。我正在尝试创建一个新的 div 元素并在该元素中添加一个名为的新类vehicles,添加 className 车辆后我试图将宽度的样式属性修改为 100px,提供的代码仅用于练习目的,即使它没有现实生活中的感觉。

const myDiv = document.getElementById("div-1");
myDiv.addEventListener("mouseover", function(event) {
  const newDiv = document.createElement("div");
  newDiv.classList.add('vehicles');
  const vehicles = document.getElementsByClassName("vehicles")[0];
  vehicles.setAttribute("style", "width: 100px");
});
#div-1 {
  background-color: red;
  color: yellow;
  width: 20px;
}

.vehicles {
border: solid 2px black;
background-color: blue;
  width: 20px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>test</title>
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <div id="div-1">
    <p>This is a test</p>
  </div>
</body>

</html>

标签: javascripthtmlcss

解决方案


您需要附加新创建的元素,然后它将起作用:

const myDiv = document.getElementById("div-1");
myDiv.addEventListener("mouseover", function(event) {
  const newDiv = document.createElement("div");
  newDiv.classList.add('vehicles');
myDiv.append(newDiv); // append the new created div
  const vehicles = document.getElementsByClassName("vehicles")[0];
  vehicles.setAttribute("style", "width: 100px");
});
#div-1 {
  background-color: red;
  color: yellow;
  width: 20px;
}

.vehicles {
border: solid 2px black;
background-color: blue;
  width: 20px;
}
<div id="div-1">
  <p>This is a test</p>
</div>


编辑(评论):

const myDiv = document.querySelector("#div-1"); // use the modern way to select element(s)
myDiv.addEventListener("mouseover", function(event) { // this is your original code
  const newDiv = document.createElement("div"); // this is also your original code
  newDiv.setAttribute("style", "width: 100px; background: black; height: 1em;"); // instead of adding class and manipulate it you can set the desired property via inline style
  myDiv.append(newDiv); // append the new created div 
});
#div-1 {
  background-color: red;
  color: yellow;
  width: 20px;
}
<div id="div-1">
  <p>This is a test</p>
</div>


推荐阅读