js实现变色
使用JavaScript实现元素变色
通过修改DOM元素的style属性或切换CSS类名实现动态变色效果。
修改内联样式
document.getElementById("targetElement").style.color = "red";
document.getElementById("targetElement").style.backgroundColor = "#00ff00";
切换CSS类名

.highlight {
color: blue;
background-color: yellow;
}
const element = document.querySelector(".myElement");
element.classList.toggle("highlight");
定时变色效果
使用setInterval实现周期性颜色变化:
const colors = ["red", "green", "blue"];
let index = 0;
setInterval(() => {
document.body.style.backgroundColor = colors[index];
index = (index + 1) % colors.length;
}, 1000);
渐变过渡效果
通过CSS过渡属性实现平滑变色:

.transition-box {
transition: background-color 0.5s ease;
width: 100px;
height: 100px;
background-color: red;
}
document.querySelector(".transition-box").addEventListener("mouseover", () => {
this.style.backgroundColor = "green";
});
响应式颜色变化
根据用户交互实时改变颜色:
const colorInput = document.getElementById("colorPicker");
colorInput.addEventListener("input", (e) => {
document.body.style.backgroundColor = e.target.value;
});
随机颜色生成
动态生成随机颜色值:
function getRandomColor() {
return `#${Math.floor(Math.random()*16777215).toString(16)}`;
}
document.getElementById("randomBtn").addEventListener("click", () => {
document.body.style.backgroundColor = getRandomColor();
});






