这是京东官网的效果图
这是我实现的简易版的放大镜
下面我们就简单的实现一下放大镜的效果吧!
html代码
<div id="zoomBox">
<div id="midArea">
<img src="img/m01.jpg" />
<div id="zoom"></div>
</div>
<div id="bigArea">
<img src="img/m01.jpg" />
</div>
<div id="smallArea">
<img src="img/m01.jpg" />
<img src="img/m02.jpg" />
</div>
</div>
css代码
<style>
img {
display: block;
}
#zoomBox {
position: relative;
width: 400px;
border: 1px solid #cecece;
}
#midArea img {
width: 400px;
height: 400px;
}
#zoom {
display: none;
position: absolute;
width: 200px;
height: 200px;
background-color: yellow;
opacity: 0.5;
cursor: move;
}
#bigArea {
display: none;
position: absolute;
width: 400px;
height: 400px;
overflow: hidden;
border: 1px solid #cecece;
left: 400px;
top: -1px;
}
#bigArea img {
position: absolute;
width: 800px;
height: 800px;
}
#smallArea {
height: 50px;
padding: 10px;
border-top: 1px solid #cecece;
}
#smallArea img {
float: left;
width: 50px;
height: 50px;
margin-right: 10px;
}
</style>
js代码
<script>
function $(id) {
return document.getElementById(id);
}
class Zoom {
constructor() {
this.zoomBox = $("zoomBox");
this.midArea = $("midArea");
this.midImg = this.midArea.children[0]; //中图
this.zoom = $("zoom"); //放大镜
this.bigArea = $("bigArea");
this.bigImg = this.bigArea.children[0]; //大图
this.smallArea = $("smallArea");
this.smallImgs = this.smallArea.children;
this.move();
}
move() {
this.midArea.onmouseover = () => {
this.zoom.style.display = "block"; //放大镜显示
this.bigArea.style.display = "block"; //大图显示
};
this.midArea.onmouseout = () => {
this.zoom.style.display = "none";
this.bigArea.style.display = "none";
};
this.midArea.onmousemove = (e) => {
let ml = this.midArea.offsetWidth - this.zoom.offsetWidth; //放大镜最大left值,限定范围
let mt = this.midArea.offsetHeight - this.zoom.offsetHeight;
//放大镜跟着鼠标走,鼠标在放大镜中间
let l =
e.pageX - this.zoomBox.offsetLeft - this.zoom.offsetWidth / 2;
let t =
e.pageY - this.zoomBox.offsetTop - this.zoom.offsetHeight / 2;
l = l <= 0 ? 0 : l >= ml ? ml : l;
t = t <= 0 ? 0 : t >= mt ? mt : t;
this.zoom.style.left = l + "px";
this.zoom.style.top = t + "px";
this.bigImg.style.left =
(-this.midArea.offsetWidth / this.zoom.offsetWidth) * l + "px";
this.bigImg.style.top =
(-this.midArea.offsetHeight / this.zoom.offsetHeight) * t + "px";
};
//图片切换
for (let i = 0; i < this.smallImgs.length; i++) {
this.smallImgs[i].onmouseover = () => {
this.midImg.src = this.bigImg.src = this.smallImgs[i].src;
};
}
}
}
new Zoom();
</script>
上面是我的代码,希望对大家可以有所帮助!