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代码部分

dart 复制代码
<style type="text/css">
	.shadow_fa {
	   /* 所有变化属性均触发动画 */
	   transition: all 1s ease-in-out;
	 }
</style>

然后是js代码

dart 复制代码
<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

相关推荐
子兮曰2 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖3 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神3 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛5 小时前
Nginx日志切分
服务器·前端·nginx
Daniel李华5 小时前
echarts使用案例
android·javascript·echarts
北原_春希5 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS5 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊5 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜5 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive5 小时前
Vue3使用ECharts
前端·javascript·echarts