JS图片放大镜效果。
应用场景:各大电商网站。
(附件)
<!-- Author: XiaoWen Create a file: 2017-01-13 12:28:36 Last modified: 2017-01-13 17:16:46 Start to work: Finish the work: Other information: --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } #box{ height: 280px; width: 480px; background: url(small.jpg) no-repeat; float:left; } #rec{ height: 100px; width: 100px; opacity:.5; background: #ccc; position: absolute; left: 0; top: 0; display:none; } #box1{ height: 400px; width: 400px; background: url(big.jpg) no-repeat; float:left; display: none; } </style> </head> <body> <div id="box"> <div id="rec"></div> </div> <div id="box1"></div> </body> <script> box.onmouseover=function(){ rec.style.display='block'; box1.style.display='block'; } box.onmousemove=function(ev){ var e=ev||event; // var ex=e.clientX; //鼠标位置不在中间 // ex=e.clientX-rec.offsetWidth/2; //鼠标位置在中间 var ex=e.clientX-rec.offsetWidth/2; var ey=e.clientY-rec.offsetHeight/2; //让小方块不超出左边 if(ex<box.offsetLeft){ ex=box.offsetLeft } //让小方块不超出右边 if(ex>box.offsetLeft+box.offsetWidth-rec.offsetWidth){ //让小方块不超出左边 ex=box.offsetLeft+box.offsetWidth-rec.offsetWidth } //让小方块不超出上边 if(ey<box.offsetTop){ ey=box.offsetTop } //让小方块不超出下边 if(ey>box.offsetTop+box.offsetHeight-rec.offsetHeight){ ey=box.offsetTop+box.offsetHeight-rec.offsetHeight } rec.style.left=ex+'px'; rec.style.top=ey+'px'; box1.style.backgroundPositionX=-4*ex+'px' box1.style.backgroundPositionY=-4*ey+'px' } box.onmouseout=function(){ rec.style.display='none'; box1.style.display='none'; } </script> </html>