In the previous article "Change the href value of the label after clicking the button through JavaScript", I introduced to you how to change the href value of the label after clicking the button through JavaScript. Interested Friends can learn about it~
Then this article will continue to introduce to you how to use JavaScript to change the background color after clicking a button.
I will introduce two methods to you below:
The first method
Note: This method uses JavaScript to change The background color when the button is clicked. After clicking the button, use the HTML DOM Style backgroundColor property to change the background color. This property is used to set the background color of the element.
The code is as follows:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:#ff311f;" > PHP中文网 </h1> <p id = "GFG_UP" style = "font-size: 16px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> 点击 </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "单击按钮更改背景颜色"; el_up.innerHTML = str; function changeColor(color) { document.body.style.background = color; } function gfg_Run() { changeColor('yellow'); el_down.innerHTML = "背景颜色已改变"; } </script> </body> </html>
The effect is as follows:
##The second method
This method uses jQuery to change the background color of the button after clicking it. The text() method is used to set the text content to the selected element; the on() method is used as an event handler for the selected element and child elements; the css() method is used to change/set the background color of the element. The code is as follows:<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> <script src ="jquery.min.js"></script> </head> <body style = "text-align:center;"> <h1 style = "color:#ff7a03;" > PHP中文网 </h1> <p id = "GFG_UP" style = "font-size: 16px; font-weight: bold;"> </p> <button> 点击 </button> <p id = "GFG_DOWN" style = "color:#ff311f; font-size: 20px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("单击按钮更改背景颜色"); $('button').on('click', function() { $('body').css('background', '#45b1ff'); $('#GFG_DOWN').text("背景颜色已改变"); }); </script> </body> </html>
JavaScript Basics Tutorial" ~ Welcome everyone to learn ~
The above is the detailed content of JavaScript implements changing the background color after clicking the button (two methods). For more information, please follow other related articles on the PHP Chinese website!