单击按钮改变按钮颜色代码
时间: 2024-06-22 18:01:23 浏览: 201
在JavaScript中,你可以使用HTML和JavaScript来实现单击按钮改变按钮颜色的简单效果。以下是一个基本示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Change Button Color</title>
<style>
.default-color { background-color: blue; }
</style>
</head>
<body>
<button id="myButton" class="default-color" onclick="changeColor()">点击我</button>
<script>
function changeColor() {
var button = document.getElementById("myButton");
if (button.classList.contains("default-color")) {
button.style.backgroundColor = "red"; // 改为红色
} else {
button.style.backgroundColor = "blue"; // 回复默认蓝色
}
}
</script>
</body>
</html>
```
在这个例子中,当用户点击带有`id="myButton"`的按钮时,会触发`changeColor()`函数。这个函数检查按钮当前的颜色,如果它是蓝色(默认状态),就将其背景颜色改为红色;如果不是蓝色(比如之前已经改过颜色),则恢复为蓝色。
阅读全文
相关推荐















