简体   繁体   中英

Using Nodelists to Change Background Color of Page

I'm trying to create two functions that will change the background color of my HTML page when the value of an input box (color selector) is changed.

Here is my JavaScript:

function backgroundColor() {
  let bod = document.getElementsByTagName("body")[0];
  let bgc = document.getElementById('bgColor');

  bgc.addEventListener("change", function(){
    color(bod, bgColor.value);
  });
}

function color(node, color){
  for (let n of node){
    n.style.backgroundColor = color;
  }
}

and the HTML:

<p>Background Color: <input type="color" id="bgColor" value="#FFFFFF"/></p>

I'm not sure how to format this, so sorry if it's unclear!

the addEventListener callback has an event param which includes the input value on it so the function should be like this

 bgc.addEventListener("change", function(event){
    bod.style.backgroundColor  = event.target.value;
  });

no need for the loop.

You have a number of different things going wrong.

  • The reference to bgColor.value should be bgc.value .
  • You never call backgroundColor() so your listener never gets added.
  • You are passing a single node to color() but then trying to iterate over it with a for() call.
  • You are using getElementsByTagName() which isn't wrong, but unless you need the live reference to the element provided byHTMLCollection you should stick with querySelector or getElementById which both return a single HTMLElement or querySelectorAll which returns a static NodeList

 function backgroundColor() { let bod = document.querySelector('body'); let bgc = document.getElementById('bgColor'); bgc.addEventListener("change", function(){ color(bod, bgc.value); }); } function color(node, color){ node.style.backgroundColor = color; } backgroundColor()
 <p>Background Color: <input type="color" id="bgColor" value="#FFFFFF"/></p>

this way (with css variable)

 document.getElementById('bt-color').addEventListener('change',function() { document.body.style.setProperty('--vColor', this.value) })
 body { --vColor: #ffffff; background-color: var(--vColor); }
 <input type="color" id="bt-color" value="#ffffff">

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