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

相关推荐
拖孩8 分钟前
【Nova UI】十四、打造组件库之按钮组件(下):按钮组组件的构建之旅
前端·javascript·vue.js
pixle08 分钟前
Vue3 Echarts 3D圆形柱状图实现教程以及封装一个可复用的组件
前端·3d·vue·echarts
Rudon滨海渔村16 分钟前
[随笔] 升级uniapp旧项目的vue、pinia、vite、dcloudio依赖包等
前端·vue.js·uni-app
机构师16 分钟前
<uniapp><插件><UTS>在uniapp中,创建自己的插件并发布到uni插件市场
javascript·uni-app·vue·插件·hbuilderx·uni
Watermelo6171 小时前
Vue3调度器错误解析,完美解决Unhandled error during execution of scheduler flush.
前端·javascript·vue.js·elementui·html·es6·bug
低代码布道师1 小时前
第一部分:网页的骨架 —— HTML
前端·html
PyAIGCMaster1 小时前
穷鬼计划:react+tailwindcss+vercel
前端·react.js·前端框架
好_快1 小时前
Lodash源码阅读-difference
前端·javascript·源码阅读
好_快1 小时前
Lodash源码阅读-differenceWith
前端·javascript·源码阅读
好_快1 小时前
Lodash源码阅读-differenceBy
前端·javascript·源码阅读