仿京东放大镜效果源码分享

看似图片是被放大了的效果,实则是一张大图实现移动,左图最小放在图片展示列表里,右侧图片最大用于展示放大镜效果

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
		<style>
			#small {
				width: 130px;
				height: 130px;
				float: left;
				margin: 100px;
				position: relative;
			}
			#small img{
				width: 100%;
				height: 100%;
			}

			#moveBox {
				width: 60px;
				height: 40px;
				background: rgba(255, 0, 0, 0.2);
				position: absolute;
				top: 0;
				cursor: all-scroll;
				display: none;
			}

			/*130/60 == 800/?*/
			#big {
				width: 369px;
				height: 246px;
				border: 1px solid blue;
				overflow: hidden;
				position: relative;
				top: 100px;
				display: none;
			}

			#big img {
				position: absolute;		
			}
		</style>
	</head>
	<body>
		<div id="small">
			<img src="small.jpg" alt="">
			<div id="moveBox"></div>
		</div>
		<div id="big">
			<img src="big.jpg" id="img">
		</div>
	</body>
</html>
<script src="./detail.js" type="text/javascript" charset="utf-8"></script>

window.addEventListener("load", function() {
	var small = document.querySelector("#small")
	var move = document.querySelector("#moveBox")
	var big = document.querySelector("#big")
	// 鼠标移小盒子显示放大区域
	small.addEventListener("mouseenter", function() {
		move.style.display = "block"
		big.style.display = "block"
	})
	// 鼠标移小盒子显示放大区域
	small.addEventListener("mouseleave", function() {
		move.style.display = "none"
		big.style.display = "none"
	})
	// 给小盒子添加鼠标移动事件
	small.addEventListener("mousemove", function(e) {
		// 计算鼠标进入小盒子的位置
		var X = e.pageX - this.offsetLeft;
		var Y = e.pageY - this.offsetTop;
		// console.log(X, Y);
		// 声明变量计算小盒子在small里XY轴的移动距离
		var moveX = X - move.offsetWidth / 2
		var moveY = Y - move.offsetHeight / 2
		// 计算move的最大移动距离
		var moveMax = small.offsetWidth - move.offsetWidth
		// 判断move盒子的left以及top值,限制移动区域在small内
		if (moveX <= 0) {
			moveX = 0;
		} else if (moveX >= moveMax) {
			moveX = moveMax
		}
		if (moveY <= 0) {
			moveY = 0;
		} else if (moveY >= moveMax) {
			moveY = moveMax + 20
		}
		// 让move跟随鼠标移动// 把鼠标定位进要移动区域盒子中心
		move.style.left = moveX + "px"
		move.style.top = moveY + "px"
		// 获取大盒子内的图片
		var bigImg = big.querySelector("#img");
		// 计算大图片最大移动距离 
		// 大图片最大移动距离=大盒子的宽度-大图片的宽度
		var bigImgMax = big.offsetWidth - bigImg.offsetWidth;
		// 大图片移动距离 = 大图片最大移动距离 * 小盒子移动距离 / 小盒子最大移动距离
		// 声明新变量接收大图片在XY轴的移动距离
		var bigMoveX = bigImgMax * moveX / moveMax
		var bigMoveY = bigImgMax * moveY / moveMax
		// 把计算出来的XY轴的移动距离赋值给大图片的left top值
		bigImg.style.left = bigMoveX + "px"
		bigImg.style.top = bigMoveY + "px"
	})
})

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值