jquery点击变色
以下是使用jQuery实现点击元素变色的几种方法:
方法一:基础点击变色
通过click事件和css方法直接修改元素颜色:
$("#targetElement").click(function() {
$(this).css("color", "red");
});
方法二:切换类名实现变色
定义CSS类并通过toggleClass切换:

.highlight {
color: blue;
background-color: yellow;
}
$(".clickable").click(function() {
$(this).toggleClass("highlight");
});
方法三:多颜色轮换
使用数组存储颜色并循环切换:
var colors = ["red", "green", "blue", "orange"];
var currentIndex = 0;
$("#colorRotate").click(function() {
currentIndex = (currentIndex + 1) % colors.length;
$(this).css("color", colors[currentIndex]);
});
方法四:带过渡动画的变色
添加CSS过渡效果使变色更平滑:

.smooth-color {
transition: color 0.3s ease, background-color 0.3s ease;
}
$(".animated").click(function() {
$(this).css({
"color": "purple",
"background-color": "pink"
});
});
方法五:根据当前状态判断变色
检查当前颜色后决定新颜色:
$("#stateCheck").click(function() {
var currentColor = $(this).css("color");
$(this).css("color", currentColor === "rgb(255, 0, 0)" ? "green" : "red");
});
注意事项:
- 确保在DOM加载完成后执行jQuery代码,可使用
$(document).ready() - 颜色值可以使用名称、十六进制或RGB格式
- 事件委托适用于动态添加的元素:
$(parent).on("click", "child", handler)






