CSS+JS 堆叠图片动态交互切换
结合DeepSeek提供的代码,终于实现了堆叠两张图片动态循环切换,以下是代码:
通过绝对定位放了两张图片
<div class="col-lg-5" style="z-index: 40; position: relative;">
<img src="images/banner_1.png" class="shadow_fa img1"
style="width: 480px; height:480px; position: absolute; top: 15%; left:16%; z-index: 10;">
<img src="images/banner_2.png" class="shadow_fa img2"
style="width: 480px; height:480px; position: absolute; top: 7%; left:24%; z-index: 9;">
</div>
然后是CSS代码部分
<style type="text/css">
.shadow_fa {
/* 所有变化属性均触发动画 */
transition: all 1s ease-in-out;
}
</style>
然后是js代码
<script>
// 获取两张图片
const img1 = document.querySelector('.img1');
const img2 = document.querySelector('.img2');
function swapImages() {
// 临时存储图片1的样式
const tempTop = img1.style.top;
const tempLeft = img1.style.left;
const tempZIndex = img1.style.zIndex;
const tempOpacity = img1.style.opacity;
// 将图片1的样式设置为图片2的当前值
img1.style.top = img2.style.top;
img1.style.left = img2.style.left;
img1.style.zIndex = img2.style.zIndex;
img1.style.opacity = img2.style.opacity;
// 将图片2的样式设置为图片1的原始值
img2.style.top = tempTop;
img2.style.left = tempLeft;
img2.style.zIndex = tempZIndex;
img2.style.opacity = tempOpacity;
// 强制触发浏览器重绘(关键代码)
void img1.offsetWidth;
}
// 每5秒执行一次
setInterval(swapImages, 5000);
</script>
QQ2025325-113356