簡體   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