使用 JavaScript 的 onClick 事件更换按钮颜色
通过 onClick 要更改按钮的颜色:
- 为按钮添加点击事件监听器。
-
每次单击按钮时,将其
style.backgroundColor
属性设置为新值。 -
可选择设置其
style.color
属性。
以下是本文示例的 HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<button id="btn">Button</button>
<script src="index.js"></script>
</body>
</html>
这是相关的 JavaScript。
const btn = document.getElementById('btn');
btn.addEventListener('click', function onClick() {
btn.style.backgroundColor = 'salmon';
btn.style.color = 'white';
});
如果每次单击按钮时都需要更改按钮的颜色,请向下滚动到下一个副标题。
我们为按钮添加了一个事件监听器。 每次单击按钮时,事件侦听器都会调用一个函数。
我们使用
style.backgroundColor
属性更改按钮的背景颜色,使用style.color
属性更改按钮的字体颜色。
每次单击时更改按钮的颜色
要在每次单击时更改按钮的颜色:
- 为按钮添加点击事件监听器。
-
每次单击按钮时,将其
style.backgroundColor
属性设置为新值。 - 使用索引变量来跟踪当前和下一个颜色。
这是此示例的 HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<button id="btn">Button</button>
<script src="index.js"></script>
</body>
</html>
这是相关的 JavaScript 代码。
const btn = document.getElementById('btn');
let index = 0;
const colors = ['salmon', 'green', 'blue', 'purple'];
btn.addEventListener('click', function onClick() {
btn.style.backgroundColor = colors[index];
btn.style.color = 'white';
index = index >= colors.length - 1 ? 0 : index + 1;
});
如果加载页面并单击按钮,我们将看到按钮的背景颜色在数组中的颜色之间交替。
我们使用了一个计数器变量来跟踪数组中颜色的索引。
每次单击按钮时,我们要么增加
index
变量中的值,要么如果最后一种颜色已经显示,则将其设置回 0。
我们使用了一个三元运算符,它与 if/else 语句非常相似。
如果问号左边的表达式求值为真值,则返回冒号左边的值,否则返回右边的值。
在示例中,我们检查索引变量存储的值是否等于或大于颜色数组中的最后一个索引。
如果我们到达最后一个索引,我们将索引变量设置回 0,否则我们将存储在变量中的值增加 1。
这样我们每次点击按钮时都能得到不同的背景颜色。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。