【发布时间】:2021-11-03 01:32:53
【问题描述】:
我正在尝试使用 onclick 将蓝色按钮变为红色,但我也希望在使用相同的 onclick 功能再次单击后按钮变回蓝色。
我该怎么做?
【问题讨论】:
-
到目前为止你有什么?提供一些代码,看看是什么问题。
标签: javascript html css button onclick
我正在尝试使用 onclick 将蓝色按钮变为红色,但我也希望在使用相同的 onclick 功能再次单击后按钮变回蓝色。
我该怎么做?
【问题讨论】:
标签: javascript html css button onclick
<!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>
【讨论】:
element.classList.add("mystyle"); 会有所帮助。然后删除它,element.classList.remove("mystyle"); 如果它“等于”一个类,则使用 element.classList.contains("mystyle");
<button class="blue round"> 那么 className 将是 "blue round" 并且它不再匹配 if 条件。像@dgood 所说的那样使用 classList 更加灵活。
你可以给按钮一个默认的背景颜色,然后添加一个click事件监听器来切换一个应用不同背景颜色的类:
document.querySelector('button').addEventListener('click', function(){ this.classList.toggle("red") })
button{
background-color:green;
}
.red{
background-color:red;
}
<button>Hello World!</button>
【讨论】:
classList,这是推荐的做法。