成品效果展示如下
代码展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>纯js制作放大镜效果</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 350px;
height: 350px;
margin-left:100px;
margin-top:100px;
border: 1px solid #000;;
position:relative;
}
#small{
width: 350px;
height: 350px;
}
#big{
position:absolute;
width: 400px;
height: 400px;
border: 1px solid #000;
right:-410px;
top:0;
overflow:hidden;
display: none;
}
#mask{
position:absolute;
width: 175px;
height: 175px;
background-color: yellow;
opacity:0.4;
top:0;
left:0;
display: none;
}
</style>
</head>
<body>
<div id="box">
<div id="small">
<img src="images/001.jpg" alt="">
<div id="mask"></div>
</div>
<div id="big">
<img src="images/0001.jpg" alt="">
</div>
</div>
<script>
var box=document.getElementById("box");
var small=document.getElementById("small");
var big=document.getElementById("big");
var smallimg=small.firstElementChild || firstChild;
var bigimg=big.firstElementChild || firstChild;
var mask=document.getElementById("mask");
//鼠标移入移出显示隐藏事件
small.onmouseenter=function(){
mask.style.display="block"
big.style.display="block"
};
//鼠标移出事件
small.onmouseleave=function(){
mask.style.display = "none"
big.style.display = "none"
};
//鼠标在盒子中的位置
small.onmousemove=function(event){
event = event || window.event;
//获取鼠标在盒子中的位置
var mousex=getEventPageXY(event).pageX-box.offsetLeft;
var mousey=getEventPageXY(event).pageY-box.offsetTop;
//鼠标在盒子中移动的距离
var movex=mousex-(mask.offsetWidth/2);
var movey=mousey-(mask.offsetHeight/2);
if(movex<=0){
movex = 0
}
if(movex>=(box.offsetWidth-mask.offsetWidth)){
movex = box.offsetWidth-mask.offsetWidth
}
if(movey<=0){
movey = 0
}
if(movey>=(box.offsetHeight-mask.offsetHeight)){
movey = box.offsetHeight-mask.offsetHeight;
}
mask.style.left = movex+"px";
mask.style.top=movey+"px";
//判断比例
//小图片/大图片=小盒子移动的距离/大图片移动的距离
var bili=smallimg.offsetWidth/bigimg.offsetWidth;
var bigx=movex/bili;
var bigy=movey/bili;
//取整
bigx=Math.floor(bigx);
bigy = Math.floor(bigy);
//移动大图片
bigimg.style.marginLeft=-bigx+"px";
bigimg.style.marginTop=-bigy+"px";
};
//获取event对象的pageXY的兼容性封装
function getEventPageXY(event){
return{
pageX:event.pageX || scroll().left+event.clientX,
pageY:event.pageY || scroll().top+event.clientY
}
}
//被卷去的头部和左边部分的兼容性封装
function scroll(){
if(window.pageXOffset!==undefined){
return{
left:window.pageXOffset,
top:window.pageYOffset
}
}else{
return{
left:document.documentElement.scrollLeft,
top:document.documentElement.scrollTop
}
}
}
</script>
</body>
</html>
支持原创,禁止盗取!
万水千山总是情,点个关注行不行!