JS 仿淘宝的放大镜效果

概述

JS 实现淘宝的放大镜效果

要实现的效果展示

在这里插入图片描述

根据遮罩来显示对应区域的展示图。

HTML

 - big        外层大盒子
 - small      遮罩盒子
 - left       小图盒子
 - right      大图盒子

<div class="big">
	<div class="left">
		<div class="small"></div>
		<img src="img/min.jpg" class="le_img"  />
	</div>
	<div class="right">
		<img src="img/max.jpg" class="ri_img" />
	</div>
</div>
CSS

.big {
	display: flex;
	justify-content: flex-start;
}

.left {
	border: solid 1px plum;
	width: 350px;
	height: 350px;
	position: relative;
}

.small {
	width: 153px;
	height: 153px;
	background: rgba(255, 255, 210, 0.7);
	position: absolute;
	top: 0;
	left: 0;
	display: none;
}

.right {
	width: 350px;
	height: 350px;
	overflow: hidden;
	position: relative;
	display: none;
}

.ri_img {
	position: absolute;
	left: 0;
	top: 0;
}
JS
// 声明变量;
var big = document.querySelector(".big");
var left = document.querySelector(".left");
var small = document.querySelector(".small");
var right = document.querySelector(".right");
var le = document.querySelector(".le_img");
var ri = document.querySelector(".ri_img");

// 设置鼠标移入
left.onmouseover = function() {
	right.style.display = "block";
	small.style.display = "block";
}

// 设置鼠标滑过小块移动;
left.onmousemove = function(e) {
	var x = e.clientX,
		y = e.clientY;
	var w = small.offsetWidth,
		h = small.offsetHeight;
		
	// 获取在盒子内部的坐标
	var X = x - w / 2;
	var Y = y - h / 2;

	if(X < 0) {
		X = 0;
		// 判定横向最大值 
	} else if(X > small.offsetWidth - w) {
		X = small.offsetWidth - w;
	}
	if(Y < 0) {
		Y = 0;
		// 判定纵向最大值
	} else if(Y > small.offsetHeight- h) {
		Y = small.offsetHeight- h;
	}
	small.style.left = X + "px";
	small.style.top = Y + "px";
	
	ri.style.left = ri.offsetWidth / le.offsetWidth * -X + "px";
	ri.style.top = ri.offsetHeight / le.offsetHeight * -Y + "px";
}

// 设置鼠标移入事件
left.onmouseout = function() {
	right.style.display = "none";
	small.style.display = "none";
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值