放大镜效果
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>放大镜效果</title> 5 <style type="text/css"> 6 .samllImg{ 7 position: relative; 8 215px; 9 height: 215px; 10 } 11 .samllImg img{ 12 215px; 13 height: 215px; 14 } 15 .samllImg span{ 16 display: none; 17 107.5px; 18 height:107.5px; 19 position: absolute; 20 top:0px; 21 left:0px; 22 background-color: rgba(100,100,10,0.3);; 23 } 24 .bigImg{ 25 display: none; 26 215px; 27 height: 215px; 28 background-image: url("image/0.jpg"); 29 background-repeat: no-repeat; 30 position: absolute; 31 left:225px; 32 top:0 33 } 34 </style> 35 </head> 36 <body> 37 <div class="samllImg"> 38 <img src="image/0.jpg"> 39 <span class="cover"></span> 40 <div class="bigImg"></div> 41 </div> 42 <script type="text/javascript"> 43 window.onload = function(){ 44 // 通过类名获取元素 45 function $(className) { 46 return document.getElementsByClassName(className)[0]; 47 } 48 // 放大镜效果 49 function magnifier(small_img,cover,big_img) { 50 $(small_img).onmouseover= function(){ 51 $(cover).style.display="block"; 52 $(big_img).style.display="block"; 53 $(small_img).onmousemove = function(e) { 54 e = e || event; //浏览器兼容 55 let left = e.pageX-$(small_img).offsetLeft-$(cover).offsetWidth*0.5; 56 let top = e.pageY-$(small_img).offsetTop-$(cover).offsetHeight*0.5; 57 left = left<=0?0:(left>$(small_img).offsetWidth-$(cover).offsetWidth+$(small_img).offsetLeft?$(small_img).offsetWidth-$(cover).offsetWidth:left); 58 top = top<=0?0:(top>$(small_img).offsetHeight-$(cover).offsetHeight+$(small_img).offsetTop?$(small_img).offsetHeight-$(cover).offsetHeight:top); 59 $(cover).style.left = left + "px"; 60 $(cover).style.top = top + "px"; 61 let leftPos = left/$(small_img).offsetWidth*430; 62 let topPos = top/$(small_img).offsetHeight*430; 63 $(big_img).style.backgroundPosition=`${-leftPos}px ${-topPos}px`; 64 } 65 } 66 $(small_img).onmouseout = function() { 67 $(cover).style.display="none"; 68 $(big_img).style.display="none"; 69 } 70 } 71 magnifier("samllImg","cover","bigImg"); 72 } 73 // 考虑一个问题:如果图片像素和盒子模型的大小不一致时,如何实现效果?(暂时还未实现) 74 </script> 75 </body> 76 </html>