j放大镜分享
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
#small-box{
width: 200px;
height: 200px;
background-image: ur## 标题l(img/0.jpg);
background-size: 200px 200px;
position: absolute;
left: 100px;
top: 200px;
}
#big-box{
width: 400px;
height: 400px;
background-image: url(img/0.jpg);
background-size: 800px 800px;
position: absolute;
left: 400px;
top: 200px;
display: none;
position: absolute;
}
#mask{
height: 100px;
width: 100px;
opacity: 0.3;
background-color: red;
display: none;
position: absolute;
}
</style>
</head>
<body>
<div id="small-box">
<div id="mask"></div>
</div>
<div id="big-box"></div>
</body>
</html>
<script>
class Magnifier{
constructor(newSmallBox,newBigBox,newMask){
this.smallBox=newSmallBox;
this.bigBox=newBigBox;
this.mask=newMask;
}
//添加鼠标移到
onmouseover(){
let that=this;
this.smallBox.onmouseover=function(){
that.bigBox.style.display="block";
that.mask.style.display="block";
}
}
//添加鼠标移开
onmouseout(){
let that=this;
this.smallBox.onmouseout=function(){
that.bigBox.style.display="none";
that.mask.style.display="none";
}
}
// //鼠标移动 拖拽效果
onmousemove(){
let that =this;
this.smallBox.onmousemove=function(evt){
let e=evt||event;
let left=e.pageX - this.offsetLeft - that.mask.offsetWidth/2;
let top=e.pageY - this.offsetTop - that.mask.offsetHeight/2;
//越界问题
if(left<0){
left=0;
}
let maxLeft=this.offsetWidth-that.mask.offsetWidth;
if(left>maxLeft){
left=maxLeft
}
if(top<0){
top=0;
}
let maxTop=this.offsetHeight-that.mask.offsetHeight;
if(top>maxTop){
top=maxTop;
}
//公式 反向运动
let x=left*that.bigBox.offsetWidth/that.mask.offsetWidth;
let y=top*that.bigBox.offsetHeight/that.mask.offsetHeight;
that.mask.style.left=left+ "px";
that.mask.style.top=top+ "px"
//水平垂直位置
that.bigBox.style.backgroundPositionX=-x+"px";
that.bigBox.style.backgroundPositionY=-y+"px";
}
}
}
let osmallBox = document.getElementById("small-box");
let omask = document.getElementById("mask");
let oBigBox=document.getElementById("big-box")
let mf= new Magnifier(osmallBox,oBigBox,omask);
mf.onmouseover();
mf.onmouseout();
mf.onmousemove();
</script>