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

相关推荐
一点七加一24 分钟前
Harmony鸿蒙开发0基础入门到精通Day09--JavaScript篇
开发语言·javascript·ecmascript
_安晓27 分钟前
Rust 中精确大小迭代器(ExactSizeIterator)的深度解析与实践
java·前端·python
烛阴27 分钟前
从create到yield:Lua协程完全上手指南
前端·lua
薛一半1 小时前
Vue3的Pinia详解
前端·javascript·vue.js
浅影歌年2 小时前
vue3模块中引用公共css变量文件
前端
盼哥PyAI实验室3 小时前
从搭建到打磨:我的纯前端个人博客开发复盘
前端·javascript
前端初见3 小时前
2025前端面试题大合集
前端
用户904706683573 小时前
vue3.5新特性——useTemplateRef
前端
嘉琪0013 小时前
vue3+ts面试题(一)JSX,SFC
前端·javascript·react.js
何贤3 小时前
🪐 行星科技概念官网!Hero Section 回归!(Three.js ✨)
前端·javascript·three.js