概述
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";
}