如何实现每5秒以滚动切换效果刷新Div?
修改Div滚动切换动画效果
原代码可实现每5秒随机显示2个Div,现调整为当前显示的Div向上滚动消失,新Div从底部向上滚动出现的循环动画,具体实现如下:
修改后的完整代码
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <div class="row"> <div class="Image">1</div> <div class="Image">2</div> <div class="Image">3</div> <div class="Image">4</div> <div class="Image">5</div> <div class="Image">6</div> <div class="Image">7</div> </div>
CSS
.row { background: red; display: flex; position: relative; overflow: hidden; height: 50px; } div.Image { display: none; width: 50px; height: 50px; background: tomato; margin: 2px; color: white; line-height: 50px; text-align: center; position: absolute; bottom: -50px; }
JavaScript
$(document).ready(function() { // 初始化加载第一组Div并完成入场动画 const initialDivs = getRandomDivs(); $(initialDivs).show().animate({ bottom: 0 }, 500, () => { setTimeout(switchDivs, 5000); }); }); function getRandomDivs() { return $("div.Image").get().sort(() => Math.round(Math.random()) - 0.5).slice(0, 2); } function switchDivs() { const currentDivs = $("div.Image:visible"); // 当前Div向上滚动出容器后隐藏 currentDivs.animate({ top: "-50px" }, 500, function() { $(this).hide().css("top", ""); // 重置定位属性,避免影响下次动画 }); // 获取不重复的新随机Div let newDivs = getRandomDivs(); while (newDivs.some(div => currentDivs.is(div))) { newDivs = getRandomDivs(); } // 新Div从底部向上滚动进入容器 $(newDivs).show().css("bottom", "-50px").animate({ bottom: 0 }, 500, () => { setTimeout(switchDivs, 5000); }); }
关键改动说明
- 容器布局调整:给
.row添加position: relative、overflow: hidden和固定高度,限制Div的移动范围,避免内容溢出。 - 元素定位控制:给
.Image设置position: absolute,初始位置在容器底部外(bottom: -50px),为入场动画做准备。 - 动画逻辑优化:
- 入场动画:通过
animate将Div从底部外移动到容器内(bottom: 0)。 - 退场动画:将当前显示的Div向上移动出容器(
top: -50px)后隐藏。 - 防重复逻辑:确保新选中的Div与当前显示的不重复,提升切换多样性。
- 入场动画:通过
内容的提问来源于stack exchange,提问作者bkoenig
相关产品推荐
相关产品推荐

