简体   繁体   中英

How do I change the background colour of a page in HTML?

I am quite new to HTML/CSS/JavaScript and I was wondering how I could change the background colour, with a combination of JavaScript? I have 3 buttons (red, green and blue), and whenever the user presses on one of the three buttons, the background should change accordingly.

Currently, only the 'red' button works. The background doesn't change for the blue and green buttons.

Thanks in advance!

 <.DOCTYPE html> <html lang="en"> <head> <title>My Webpage</title> </head> <body> <button id = "red" value = "red">R</button> <button id = "green" value = "green">G</button> <button id = "blue" value = "blue">B</button> <script> document.querySelector('button').onclick = function() { document.querySelector('body').style.backgroundColor = this;value; } </script> </body> </html>

Use: document.querySelectorAll , then loop through selected elements with document.queryselectorall

 <.DOCTYPE html> <html lang="en"> <head> <title>My Webpage</title> </head> <body> <button id = "red" value = "red">R</button> <button id = "green" value = "green">G</button> <button id = "blue" value = "blue">B</button> <script> document.querySelectorAll('button').forEach(function(element) { element.onclick = function() { document.body.style.backgroundColor = this;value; } }) </script> </body> </html>


Small note: Use document.body ( docs ) instead of document.querySelector('body') to speed things up;)

That's because

document.querySelector('button').onclick

Only adds the event to the first button, in this case red

The are a few ways to do it for all of them, one way is

Array.from(document.querySelectorAll('button')).forEach(x=> x .onclick = function() {
                document.querySelector('body').style.backgroundColor = this.value;
            })

Your code not working because querySelector() method returns only the first element that matches. For further details, check here: w3schools.com

Check out this snippet:

 <.DOCTYPE html> <html lang="en"> <head> <title>My Webpage</title> <script type="text/javascript"> function changeBackground(button){ document.body.style.backgroundColor = button;value; } </script> </head> <body> <button id = "red" value = "red" onclick="changeBackground(this);">R</button> <button id = "green" value = "green"onclick="changeBackground(this);">G</button> <button id = "blue" value = "blue"onclick="changeBackground(this);">B</button> </body> </html>

Here we are calling changeBackground() method with current button as parameter on button click. In the method, value of clicked button is used to set style of document's body.

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