当前位置:首页 > JavaScript

js实现百叶窗

2026-04-03 19:40:20JavaScript

实现百叶窗效果的 JavaScript 方法

百叶窗效果可以通过动态调整多个水平或垂直条带的透明度或高度来实现。以下是使用纯 JavaScript 和 CSS 创建百叶窗效果的步骤:

HTML 结构

<div id="blinds-container">
  <div class="blind"></div>
  <div class="blind"></div>
  <div class="blind"></div>
  <!-- 更多条带... -->
</div>

CSS 样式

#blinds-container {
  position: relative;
  width: 600px;
  height: 400px;
  overflow: hidden;
}

.blind {
  position: absolute;
  width: 100%;
  height: 40px; /* 每条高度 */
  background-color: #333;
  transform-origin: top;
  transition: transform 0.5s ease;
}

JavaScript 实现

const container = document.getElementById('blinds-container');
const blindCount = 10; // 条带数量
const duration = 1000; // 动画持续时间(ms)

// 创建条带
for (let i = 0; i < blindCount; i++) {
  const blind = document.createElement('div');
  blind.className = 'blind';
  blind.style.top = `${(i * container.offsetHeight) / blindCount}px`;
  blind.style.height = `${container.offsetHeight / blindCount}px`;
  container.appendChild(blind);
}

// 动画函数
function animateBlinds() {
  const blinds = document.querySelectorAll('.blind');
  blinds.forEach((blind, index) => {
    setTimeout(() => {
      blind.style.transform = 'scaleY(0)';
    }, (index * duration) / blinds.length);
  });
}

// 重置函数
function resetBlinds() {
  const blinds = document.querySelectorAll('.blind');
  blinds.forEach(blind => {
    blind.style.transform = 'scaleY(1)';
  });
}

// 点击触发动画
container.addEventListener('click', () => {
  resetBlinds();
  setTimeout(animateBlinds, 300);
});

替代实现方法(使用 CSS 动画)

@keyframes blindAnimation {
  0% { transform: scaleY(1); }
  100% { transform: scaleY(0); }
}

.blind {
  animation: blindAnimation 1s forwards;
  animation-delay: calc(var(--index) * 0.1s);
}
// 设置CSS变量
document.querySelectorAll('.blind').forEach((blind, index) => {
  blind.style.setProperty('--index', index);
});

水平百叶窗变体

要实现水平方向的百叶窗效果,只需修改 CSS:

.blind {
  width: 40px; /* 每条宽度 */
  height: 100%;
  transform-origin: left;
  transform: scaleX(1);
}

然后修改 JavaScript 中的 transform 为 scaleX(0)

js实现百叶窗

性能优化建议

  1. 使用 will-change: transform 提升动画性能
  2. 对于复杂场景,考虑使用 CSS clip-path 替代 transform
  3. 使用 requestAnimationFrame 实现更流畅的动画
  4. 避免在动画期间触发重排操作

这些方法可以创建从简单到复杂的百叶窗效果,根据实际需求调整条带数量、动画时间和方向等参数。

标签: 百叶窗js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…

js实现 功能

js实现 功能

在 JavaScript 中实现功能通常涉及多个关键步骤,具体取决于功能需求。以下是常见功能的实现方法和示例: 基本功能实现 使用函数封装逻辑是最直接的方式。例如,实现一个计算两数之和的函数: f…

js实现上传图片

js实现上传图片

使用HTML5的File API实现图片上传 HTML5的File API允许通过JavaScript访问用户选择的文件。需要创建一个文件输入元素,并监听其change事件。 <input t…