JS实现放大器效果

3 篇文章 0 订阅
2 篇文章 0 订阅

CSS样式

<style>
		* {
			margin: 0;
			padding: 0;
		}

		.father {
			margin: 100px;
			width: 1000px;
			height: 500px;
			position: relative;
		}

		.small {
			width: 295px;
			height: 201px;
			position: relative;
			background-image: url(下载.jpg);
			background-size: cover;
		}

		.small_a {
			position: absolute;
			top: 0;
			left: 0;
			height: 100px;
			width: 100px;
			background: rgba(0, 0, 0, .3);
			display: none;
		}
		.big {
			position: absolute;
			top: 0px;
			left: 295px;
			width: 295px;
			height: 201px;
			overflow: hidden;
			display: none;
		}

		.big img {
			position: absolute;
			display: block;
			width: 295%;
			height: 201%;
			top: 0;
			right: 0;
		}
	</style>

html样式

<div class="father">
		<div class="small">
			<div class="small_a"></div>
		</div>
		<div class="big">
			<img src="下载.jpg" alt="">
		</div>
	</div>

JS样式

<script>
		// 定义div
		const small = document.querySelector(".small")
		const bigImg = document.querySelector(".big img")
		const b = document.querySelector(".big")
		const smallA = document.querySelector(".small_a")
		// 创建鼠标移入事件
		small.onmouseover = function (e) {
			// 进行事件委托,并且消除兼容性
			e = e || window.event
			// 鼠标移入后smallA与display属性为block
			smallA.style.display = "block"
			b.style.display = "block"
			document.onmousemove = function (e) {
				e = e || window.event
				// 获取鼠标当前坐标
				let startX = e.clientX-50
				let startY = e.clientY-50
				// 获取当前盒子的大小
				let x=smallA.offsetWidth;
				let y=smallA.offsetHeight;
				// 将鼠标当前位置减去盒子大小
				let addrresX=startX-x
				let addrresY=startY-y
				// 进行严谨化,设置临界值
				// 当位置超过边界为负时,为0
				if(addrresX<0){
					addrresX=0
				}
				if(addrresY<0){
					addrresY=0
				}
				// 当位置超过父级盒子大小减去自身盒子大小时为最大值
				if(addrresX>small.clientWidth-x){
					addrresX=small.clientWidth-x
				}
				if(addrresY>small.clientHeight-y){
					addrresY=small.clientHeight-y
				}
				smallA.style.left=addrresX+"px"
				smallA.style.top=addrresY+"px"
				// 进行照片的倍数转换
				// 原则为按比例划分  smallA/small的背景图=big/bigImg
				// 所以当比例为X2.01,Y2.95
				bigImg.style.top=-addrresY*2.01+"px"
				bigImg.style.left=-addrresX*2.95+"px"
			}

		}
		small.onmouseout = function (e) {
			// 进行事件委托,并且消除兼容性
			e = e || window.event
			// 鼠标移出后smallA与display属性为none
			smallA.style.display = "none"
			b.style.display = "none"
			// 鼠标移出后鼠标移动为null
			document.onmousemove = null;
		}
	</script>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值