1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <style> 7 #div1,#div2{ 8 float: left; 9 310px; 10 height: 310px; 11 position: relative; 12 margin:10px; 13 } 14 #div1 div{ 15 100px; 16 height: 100px; 17 position: absolute; 18 left: 0; 19 top: 0; 20 background-color: yellow; 21 opacity:.5; 22 filter:alpha(opacity=50); 23 display: none; 24 } 25 #div1 img{ 26 310px; 27 height: 310px; 28 } 29 #div2{ 30 overflow: hidden; 31 display: none; 32 } 33 #div2 img{ 34 800px; 35 height: 800px; 36 position: absolute; 37 left: 0; 38 top: 0; 39 } 40 </style> 41 <script> 42 window.onload=function(){ 43 var oDiv1=document.getElementById('div1'); 44 var oMask=oDiv1.children[1]; 45 var oDiv2=document.getElementById('div2'); 46 var oImg=oDiv2.children[0]; 47 oDiv1.onmouseover=function(){ 48 oDiv2.style.display='block'; 49 oMask.style.display='block'; 50 }; 51 oDiv1.onmouseout=function(){ 52 oDiv2.style.display='none'; 53 oMask.style.display='none'; 54 }; 55 document.onmousemove=function(ev){ 56 var ev=ev||event; 57 58 var t=ev.clientY-oDiv1.offsetTop-oMask.offsetHeight/2; 59 var l=ev.clientX-oDiv1.offsetLeft-oMask.offsetWidth/2; 60 61 if(t<0){ 62 t=0; 63 }else if(t>oDiv1.offsetHeight-oMask.offsetHeight){ 64 t=oDiv1.offsetHeight-oMask.offsetHeight 65 } 66 if(l<0){ 67 l=0; 68 }else if(l>oDiv1.offsetWidth-oMask.offsetWidth){ 69 l=oDiv1.offsetWidth-oMask.offsetWidth 70 } 71 72 oMask.style.top=t+'px'; 73 oMask.style.left=l+'px'; 74 75 var T=-t*(oImg.offsetHeight-oDiv2.offsetHeight)/(oDiv1.offsetHeight-oMask.offsetHeight); 76 var L=-l*(oImg.offsetWidth-oDiv2.offsetWidth)/(oDiv1.offsetWidth-oMask.offsetWidth); 77 78 oImg.style.top=T+'px'; 79 oImg.style.left=L+'px'; 80 }; 81 }; 82 </script> 83 </head> 84 <body> 85 <div id="div1"> 86 <img src="img/2.jpg" alt=""> 87 <div></div> 88 </div> 89 <div id="div2"> 90 <img src="img/2.jpg" alt=""> 91 </div> 92 </body> 93 </html>
放大镜主要应用于商城物品的放大,里面设计了offsetTop,clientHeight等物体信息的转换,右边图片的放大就是左边图片的比例放大,移黄色小块,右边等比例移动。