<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>图片放大镜效果</title> <style> *{ padding: 0; margin: 0; } body{ padding: 50px; position: relative; } .goods { width: 220px; height: 200px; position: relative; overflow: hidden; } .goods img{ width: 220px; height: 200px; } span{ width: 100px; height: 100px; position: absolute; background-color: yellow; left: 0; top: 0; opacity: 0.5; display: none; } #show{ width: 400px; height: 400px; border: 1px solid #ccc; position: absolute; left: 300px; top: 50px; display: none; overflow: hidden; } #show img{ position: absolute; } </style> </head> <body> <div class="goods"> <img src="img/5.jpg" alt="" /> <span></span> </div> <div id="show"> <img src="img/5.jpg" alt="" /> </div> </body> <script src="js/jquery-1.11.3.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> //first complete the movement of the yellow pic $('.goods').on('mouseover',function(){ $('span').show(); $('#show').show(); var maxHeight = $('.goods').height() - $('span').height(); var maxWeight = $('.goods').width() - $('span').width(); $('.goods').on('mousemove',function(e){ var x = e.clientX; var y = e.clientY; var cy = y - $('.goods').offset().top - $('span').width()/2; var cx = x - $('.goods').offset().left - $('span').width()/2; if(cx < 0) cx = 0; if(cy < 0) cy =0; if(cy > maxHeight) cy = maxHeight; if(cx > maxWeight) cx = maxWeight; var percentX = $('span').position().left/$('.goods').width(); var percentY = $('span').position().top/$('.goods').height(); $('span').css({ left:cx, top :cy }) $('#show').find('img').css({ top : -percentY*$('#show').find('img').height(), left : -percentX*$('#show').find('img').width() }) }); }).on('mouseout',function(){ $('span').hide(); $('#show').hide(); }); </script> </html>
预览效果图: