Flutter中Animated Container轮播动画效果实现指导请求
实现指导:循环轮播的半屏模糊容器效果
核心思路
通过CSS定位+过渡动画控制容器的位置、缩放与模糊状态,配合JavaScript定时逻辑实现三个容器的循环切换:当前容器全屏显示在前端,另外两个容器各占半屏并带模糊效果,到设定时长后自动切换下一个容器至前端。
分步实现
1. HTML结构
用一个父容器包裹三个子容器,每个子容器承载自定义内容:
<div class="carousel-container"> <div class="carousel-item active">容器1内容</div> <div class="carousel-item">容器2内容</div> <div class="carousel-item">容器3内容</div> </div>
2. CSS样式
- 父容器设为相对定位,占满整个视口并隐藏溢出内容;
- 子容器默认绝对定位,仅显示半屏并添加模糊,
active类标记当前前端容器(全屏、无模糊、层级最高); - 定义过渡动画,让切换过程更平滑:
.carousel-container { position: relative; width: 100vw; height: 100vh; overflow: hidden; } .carousel-item { position: absolute; width: 50vw; height: 100vh; top: 0; filter: blur(4px); transition: all 0.8s ease; display: flex; align-items: center; justify-content: center; font-size: 2rem; color: #fff; } /* 默认布局:左、中、右各半屏 */ .carousel-item:nth-child(1) { left: -50%; } .carousel-item:nth-child(2) { left: 0; } .carousel-item:nth-child(3) { left: 50%; } /* 前端容器状态:全屏居中、无模糊、层级置顶 */ .carousel-item.active { left: 0; width: 100vw; filter: blur(0); z-index: 10; } /* 切换时的辅助定位类 */ .carousel-item.prev { left: -50%; } .carousel-item.next { left: 50%; }
3. JavaScript逻辑
- 定时触发切换逻辑,更新容器的
active状态; - 处理循环索引,确保三个容器无限轮播:
const items = document.querySelectorAll('.carousel-item'); let currentIndex = 0; const intervalTime = 3000; // 切换间隔(毫秒) function rotateCarousel() { // 清除所有容器的状态类 items.forEach(item => { item.classList.remove('active', 'prev', 'next'); }); // 更新当前索引,实现循环 currentIndex = (currentIndex + 1) % items.length; // 标记当前前端容器 items[currentIndex].classList.add('active'); // 标记左侧半屏容器 const prevIndex = (currentIndex - 1 + items.length) % items.length; items[prevIndex].classList.add('prev'); // 标记右侧半屏容器 const nextIndex = (currentIndex + 1) % items.length; items[nextIndex].classList.add('next'); } // 初始化状态 items[currentIndex].classList.add('active'); items[2].classList.add('prev'); items[1].classList.add('next'); // 启动自动轮播 setInterval(rotateCarousel, intervalTime);
4. 效果自定义建议
- 模糊强度:修改
filter: blur(4px)的数值,调整半屏容器的模糊程度; - 动画速度:修改
transition: all 0.8s ease的0.8s,控制切换动画的时长; - 内容扩展:子容器可替换为图片、卡片等任意元素,只需调整内部样式即可;
- 交互增强:可添加左右切换按钮,通过调用
rotateCarousel函数实现手动切换。
内容的提问来源于stack exchange,提问作者Hanan Bhutta
相关产品推荐
相关产品推荐

