我試圖通過使用 onclick 將藍色按鈕變成紅色,但是我也希望在使用相同的 onclick 功能再次單擊后該按鈕變回藍色。
我該怎么做?
uj5u.com熱心網友回復:
<!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>
uj5u.com熱心網友回復:
您可以為按鈕提供默認背景顏色,然后向其添加一個click事件偵聽器,以切換應用不同背景顏色的類:
document.querySelector('button').addEventListener('click', function(){ this.classList.toggle("red") })
button{
background-color:green;
}
.red{
background-color:red;
}
<button>Hello World!</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345967.html
標籤:javascript html css 按钮 点击
下一篇:如何為物件屬性的可變參考賦值?
