当前位置:首页 > JavaScript

js实现关灯

2026-02-01 09:33:21JavaScript

实现关灯效果的JavaScript方法

使用CSS和JavaScript结合的方式可以模拟关灯效果,通常通过调整页面亮度或覆盖遮罩层实现。

HTML结构

<button id="toggleLight">关灯</button>
<div id="content">页面内容区域</div>

CSS样式

#content {
  transition: all 0.5s ease;
}
.dark-mode {
  background-color: #222;
  color: #eee;
  /* 可选:添加遮罩层 */
  position: relative;
}
.dark-mode::after {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  z-index: 999;
}

JavaScript代码

js实现关灯

const toggleBtn = document.getElementById('toggleLight');
const content = document.getElementById('content');

toggleBtn.addEventListener('click', function() {
  content.classList.toggle('dark-mode');
  this.textContent = content.classList.contains('dark-mode') ? '开灯' : '关灯';
});

更高级的实现方案

对于需要保存用户偏好的场景,可以结合localStorage:

// 检查本地存储
if (localStorage.getItem('darkMode') === 'true') {
  content.classList.add('dark-mode');
  toggleBtn.textContent = '开灯';
}

toggleBtn.addEventListener('click', function() {
  content.classList.toggle('dark-mode');
  const isDark = content.classList.contains('dark-mode');
  localStorage.setItem('darkMode', isDark);
  this.textContent = isDark ? '开灯' : '关灯';
});

使用CSS变量实现主题切换

现代浏览器支持CSS变量,可以实现更灵活的主题切换:

js实现关灯

CSS

:root {
  --bg-color: #fff;
  --text-color: #333;
}
.dark-mode {
  --bg-color: #222;
  --text-color: #eee;
}
body {
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: all 0.5s ease;
}

JavaScript

document.documentElement.classList.toggle('dark-mode');

性能优化建议

对于大型页面,使用CSS滤镜可能比覆盖遮罩层更高效:

.dark-mode {
  filter: brightness(0.3);
}

这种方法通过GPU加速,对性能影响较小,但会改变所有元素的显示效果。

标签: js
分享给朋友:

相关文章

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Promise…

js实现轮播图

js实现轮播图

基础轮播图实现 使用HTML、CSS和JavaScript实现一个简单的自动轮播图。HTML结构包含一个容器和多个图片项。 <div class="slider"> <div…

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…