繁体   English   中英

给新创建的div添加类名并修改样式

[英]Add class name to a newly created div and modify style

我试图通过 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>

您刚刚创建了一个新元素。 您必须将此元素添加到 DOM 树中。

例如,

document.body.appendChild(newDiv);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM