在JavaScript中实现点击切换背景的功能,主要涉及到DOM操作和事件监听。下面是一个基础的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>背景切换</title>
<style>
body {
transition: background-color 0.5s ease;
}
.bg-color-1 { background-color: #ffcccc; }
.bg-color-2 { background-color: #ccffcc; }
.bg-color-3 { background-color: #ccccff; }
</style>
</head>
<body class="bg-color-1">
<button id="toggle-bg">切换背景</button>
<script src="script.js"></script>
</body>
</html>
document.addEventListener('DOMContentLoaded', function() {
const body = document.body;
const button = document.getElementById('toggle-bg');
let currentColorIndex = 0;
const colors = ['bg-color-1', 'bg-color-2', 'bg-color-3'];
button.addEventListener('click', function() {
// 移除当前背景颜色类
body.classList.remove(colors[currentColorIndex]);
// 计算下一个颜色的索引
currentColorIndex = (currentColorIndex + 1) % colors.length;
// 添加新的背景颜色类
body.classList.add(colors[currentColorIndex]);
});
});
DOMContentLoaded
事件确保DOM完全加载后再执行脚本。transition: background-color 0.5s ease;
。DOMContentLoaded
事件确保DOM完全加载后再执行脚本。通过以上方法,你可以轻松实现点击切换背景的功能,并根据需要进行扩展和优化。
没有搜到相关的文章