用JS写放大镜效果
样式(style)
` *{
margin:0;
padding:0;
}
.cont{width:1000px;margin:0 auto;}
.cont::after{
content:"";
width:0;
height:0;
overflow:hidden;
clear:both;
display:block;
}
.small_box{
width:300px;
height:300px;
float:left;
position:relative;
border:1px solid red;
}
.small_box img{
width:300px;
height:300px;
}
.small_box span{
background:rgba(255,255,124,0.7);
display:block;
position:absolute;
left:0;
top:0;
display:none;
}
.big_box{
width:300px;
height:300px;
float:left;
display:none;
overflow:hidden;
margin-left:100px;
border:1px solid red;
position:relative;
}
.big_box img{
width:600px;
height:600px;
position:absolute;
left:0;
top:0;
} `
结构(Body)
<div class="cont">
<div class="small_box">
<img src="phone.jpg" alt="">
<span></span>
</div>
<div class="big_box">
<img src="phone.jpg" alt="">
</div>
</div>
JS
function Magnifier(){
this.span = document.querySelector(".small_box span");
this.sBox = document.querySelector(".small_box");
this.bBox = document.querySelector(".big_box");
this.bImg = document.querySelector(".big_box img");
// console.log(this.bImg);
this.addEvent();
}
Magnifier.prototype.addEvent = function(){
var that = this;
this.sBox.onmouseover = function(){
that.show();
}
this.sBox.onmouseout = function(){
that.hide();
}
this.sBox.onmousemove = function(eve){
var e = eve || window.event;
that.move(e);
}
}
Magnifier.prototype.show = function(){
this.span.style.display = "block";
this.bBox.style.display = "block";
// console.log(this.bBox.offsetWidth);
console.log(this.bImg.offsetWidth);
console.log(this);
this.span.style.width = (this.bBox.offsetWidth/this.bImg.offsetWidth)*this.sBox.offsetWidth + "px";
this.span.style.height = (this.bBox.offsetHeight/this.bImg.offsetHeight)*this.sBox.offsetHeight + "px";
this.sBoxW = this.sBox.offsetWidth;
this.sBoxH = this.sBox.offsetHeight;
this.sBoxL = this.sBox.offsetLeft;
this.sBoxT = this.sBox.offsetTop;
this.spanW = this.span.offsetWidth;
this.spanH = this.span.offsetHeight;
this.bBoxW = this.bBox.offsetWidth;
this.bBoxH = this.bBox.offsetHeight;
this.bImgH = this.bImg.offsetHeight;
this.bImgW = this.bImg.offsetWidth;
}
Magnifier.prototype.hide = function(){
this.span.style.display = "none";
this.bBox.style.display = "none";
}
Magnifier.prototype.move = function(e){
var l = e.clientX-this.sBoxL-this.spanW/2;
var t = e.clientY- this.sBoxT-this.spanH/2;
if(l<0) l = 0;
if(t<0) t = 0;
if(l>this.sBoxW-this.spanW) l= this.sBoxW-this.spanW;
if(t>this.sBoxH-this.spanH) t = this.sBoxH-this.spanH;
this.span.style.left = l + "px";
this.span.style.top = t + "px";
var x = l / (this.sBoxW-this.spanW);
var y = t / (this.sBoxH-this.spanH);
this.bImg.style.left = -Math.abs(this.bImgW-this.bBoxW)*x + "px";
this.bImg.style.top = -Math.abs(this.bImgH-this.bBoxH)*y + "px";
}
new Magnifier();
![手机细节放大镜](https://img-blog.csdnimg.cn/20210111112914502.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xvcmVuYV8=,size_16,color_FFFFFF,t_70#pic_center)