<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>放大镜效果</title> <style type="text/css"> *{ margin: 0; padding: 0; } #main{ position: relative; margin: 100px auto; width: 1196px; height: 496px; border: 2px solid #ccc; } #small{ position: absolute; width: 200px; height: 200px; top: 150px; background-color: palegoldenrod; } #small img{ width: 200px; height: 200px; } #big{ position: absolute; width: 400px; top: 50px; left: 220px; height: 400px; display: none; overflow: hidden; } #big img{ width: 700px; height: 700px; position: absolute; } #lucency{ position: absolute; width: 100px; top: 0px; height: 100px; background-color: yellow; opacity: 0.5; display: none; } </style> </head> <body> <div id="main"> <div id="small"> <img src="img/shuju.jpg" /> <div id="lucency"> </div> </div> <div id="big"> <img src="img/shuju.jpg" class="bigImg" /> </div> </div> <script> var small=document.getElementById('small'); //小盒子 var luncency=document.getElementById('lucency'); //黄色盒子 var big=document.getElementById('big'); var main=document.getElementById('main') var bigImg=document.querySelector('.bigImg') small.addEventListener('mouseover',function(){//鼠标放入预览图小盒子,大图和黄色显示 big.style.display='block'; luncency.style.display='block' }) small.addEventListener('mouseout',function(){//鼠标离开预览图小盒子,大图和黄色隐藏 big.style.display='none'; luncency.style.display='none' }) small.addEventListener('mousemove',function(e){ var smallLeft=e.pageX-main.offsetLeft //鼠标距离small左边的距离 var smallTop=e.pageY-main.offsetTop-small.offsetTop //鼠标距离small上边的距离 var smllle=smallLeft-luncency.offsetWidth/2 var smllto=smallTop-luncency.offsetHeight/2 var smllMax=small.offsetWidth-luncency.offsetWidth //遮挡层的最大移动距离 if(smllle<=0 ){ smllle=0 }else if(smllle>=smllMax){ //遮挡层的最大移动距离不能超出 smllle=100 } if(smllto<=0){ smllto=0 }else if(smllto>=smllMax){ smllto=100 } luncency.style.left=smllle+'px' //黄块跟着光标坐标走,黄块的左坐标 luncency.style.top=smllto+'px' //黄块跟着光标坐标走,黄块的纵坐标 // var bigMax=big.offsetWidth-bigImg.offsetWidth //大图片的最大移动 距离 // 大图片的移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层的最大移动距离 //大图片移动距离的x var bigX=smllle*bigMax/smllMax; //大图片移动距离的Y var bigY=smllto*bigMax/smllMax; bigImg.style.left=bigX+'px' bigImg.style.top=bigY+'px' }) </script> </body> </html>