简体   繁体   中英

i want to create element (span or div) with style( specific background-color) into parent element when click on btn?

i want to create element (span or div) with style( specific background-color) into parent element when click on btn?

function openNav() {
document.getElementById("sidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
var body = document.getElementsByTagName("body")[0],
blackback = document.createElement("span"),
styleSpan = blackback.style.backgroundColor = "rgba(0,0,0,0.4)";
body.appendChild(styleSpan);
}

This line was wrong: styleSpan = blackback.style.backgroundColor = "rgba(0,0,0,0.4)";

You didn't need to reassign when giving the style to blackback and you needed to pass the blackback to the appendChild method because this is the element you've tried to create.

Try like this:

function openNav() {
  document.getElementById("sidenav").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
  var body = document.getElementsByTagName("body")[0];
  var blackback = document.createElement("span");
  blackback.style.backgroundColor = "rgba(0,0,0,0.4)";
  blackback.style.width= "250px";
  blackback.style.height= "250px";
  body.appendChild(blackback);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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