javascript - 将类名添加到新创建的 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>
解决方案
您需要附加新创建的元素,然后它将起作用:
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>
推荐阅读
- shell - 在radare2(VS shell和VS gdb)(linux)中插入文件作为用户输入
- scala - 如何让 Gradle、Scoverage 和 Sonarqube 正常工作?
- optimization - 通用“fminsearch”没有特定的子程序
- maven - 我可以将 Maven 本地存储库保留在另一台机器上并在我的项目中使用它吗?
- javascript - 吸嘴node.js;未捕获的 TypeError:回调不是函数
- windows - Windows 10 默认附带哪些编程语言(无需安装)?
- php - 使用 2 个不同类别的注册表类型
- c - 如何在 C 中正确使用 fscanf 函数?
- amazon-s3 - AWS S3 / EC2:使用文件保护程序下载文件给出CORS错误
- flutter - 如何使用 StreamBuilder 从 firestore 添加/获取数据
在颤抖?