简体   繁体   English

如何编写一个 javascript 函数来来回切换按钮颜色?

[英]How do I program a javascript function to switch button colors back and forth?

I'm trying to turn a blue button red by using an onclick, but then I also want the button to turn back to being blue after clicking again using the same onclick function.我试图通过使用 onclick 将蓝色按钮变成红色,但是我也希望在使用相同的 onclick 功能再次单击后该按钮变回蓝色。

How would I do this?我该怎么做?

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .round { border-radius: 5px; color: aliceblue; } .blue { background-color: blue; } .red { background-color: red; } </style> </head> <body> <button id="btn" class="round blue" onclick="clickBtn()">button</button> <script> function clickBtn() { let btn = document.getElementById('btn') if(btn.classList.contains('blue')) { btn.classList.remove('blue') btn.classList.add('red') } else { btn.classList.remove('red') btn.classList.add('blue') } } </script> </body> </html>

You can give the button a default background color, then add a click event listener to it which toggles a class that applies a different background color:您可以为按钮提供默认背景颜色,然后向其添加一个click事件侦听器,以切换应用不同背景颜色的类:

 document.querySelector('button').addEventListener('click', function(){ this.classList.toggle("red") })
 button{ background-color:green; } .red{ background-color:red; }
 <button>Hello World!</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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