要使用JavaScript实现开关灯效果,通常会结合HTML和CSS来完成。以下是一个简单的示例,展示如何创建一个按钮来切换页面的背景颜色,模拟开关灯的效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>开关灯效果</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="toggleButton">关灯</button>
<script src="script.js"></script>
</body>
</html>
body {
transition: background-color 0.5s, color 0.5s;
}
.light-mode {
background-color: white;
color: black;
}
.dark-mode {
background-color: black;
color: white;
}
button {
margin-top: 50px;
padding: 10px 20px;
font-size: 16px;
}
document.addEventListener('DOMContentLoaded', (event) => {
const toggleButton = document.getElementById('toggleButton');
const body = document.body;
// 检查本地存储以确定初始模式
if (localStorage.getItem('mode') === 'dark') {
body.classList.add('dark-mode');
toggleButton.textContent = '开灯';
} else {
body.classList.add('light-mode');
toggleButton.textContent = '关灯';
}
toggleButton.addEventListener('click', () => {
if (body.classList.contains('dark-mode')) {
body.classList.remove('dark-mode');
body.classList.add('light-mode');
toggleButton.textContent = '关灯';
localStorage.setItem('mode', 'light');
} else {
body.classList.remove('light-mode');
body.classList.add('dark-mode');
toggleButton.textContent = '开灯';
localStorage.setItem('mode', 'dark');
}
});
});
body
的类名,从而改变页面的背景色和文字颜色,并更新按钮文本。localStorage
保存用户的模式选择,这样即使刷新页面,设置也会被保留。这个示例展示了如何使用JavaScript来控制页面的视觉效果,通过简单的DOM操作和事件监听来实现交互功能。
领取专属 10元无门槛券
手把手带您无忧上云