代码如下
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <title></title> 7 <link rel="stylesheet" href=""> 8 <script type="text/javascript" src="js/common.js"></script> 9 <style type="text/css"> 10 body,div,img{padding:0;margin:0;} 11 #main{ 12 margin:50px; 13 position:relative; 14 15 } 16 #small{ 17 width:300px; 18 height:187px; 19 border:1px solid red; 20 21 } 22 23 #small img{ 24 width:300px; 25 height:187px; 26 } 27 #small #mark{ 28 width:50px; 29 height:50px; 30 background-color: #ccc; 31 opacity:0.5; 32 position:absolute; 33 top:0px; 34 left:0px; 35 display:none; 36 } 37 #big{ 38 width:300px; 39 height:187px; 40 border:1px solid red; 41 position:absolute; 42 top:0px; 43 left:320px; 44 overflow:hidden; 45 display:none; 46 } 47 /*图片想要移动必须绝对定位*/ 48 #big img { 49 position:absolute; 50 } 51 </style> 52 <script type="text/javascript"> 53 window.onload = function(){ 54 var oSmall = $('small'); 55 var oBig = $('big'); 56 var oMark = $('mark'); 57 var bigImg = oBig.getElementsByTagName('img')[0]; 58 59 oSmall.onmouseover = function(){ 60 oMark.style.display = 'block'; 61 oBig.style.display = 'block'; 62 } 63 64 oSmall.onmouseout = function(){ 65 oMark.style.display = 'none'; 66 oBig.style.display = 'none'; 67 } 68 69 oSmall.onmousemove = function(e){ 70 var ev = e || window.event; 71 72 //鼠标在small小图里面的距离 73 var x = ev.clientX - oSmall.parentNode.offsetLeft; 74 var y = ev.clientY - oSmall.parentNode.offsetTop; 75 76 //确定镜头的坐标 77 var markLeft = x - (mark.offsetWidth/2); 78 var markTop = y - (mark.offsetHeight/2); 79 80 81 //控制镜头边界 82 //如果距离左边小于0,就重新赋值为0 83 if (markLeft < 0) { 84 markLeft = 0; 85 } 86 //如果距离顶部小于0,就重新赋值为0 87 if (markTop < 0) { 88 markTop = 0; 89 } 90 //如果镜头的右边移动的距离加上本身的宽度大于small小图的宽度,说明右边过界了 91 if (markLeft+oMark.offsetWidth > oSmall.offsetWidth) { 92 markLeft = oSmall.offsetWidth - oMark.offsetWidth; 93 } 94 95 //如果镜头的下面移动的距离加上本身的高度大于small小图的高度,说明底部过界了 96 if (markTop+oMark.offsetHeight > oSmall.offsetHeight) { 97 markTop = oSmall.offsetHeight - oMark.offsetHeight; 98 } 99 //设置镜头的位置 100 oMark.style.left = markLeft + 'px'; 101 oMark.style.top = markTop + 'px'; 102 103 //计算大图移动的比例算法 104 //markLeft/(oSmall.offsetWidth-oMark.offsetWidth) == 105 //bigLeft/(bigImg.offsetWidth-big.offsetWidth) 106 // 107 var bigLeft = markLeft/(oSmall.offsetWidth-oMark.offsetWidth) * (bigImg.offsetWidth-big.offsetWidth); 108 var bigTop = markTop/(oSmall.offsetHeight-oMark.offsetHeight) * (bigImg.offsetHeight-big.offsetHeight); 109 110 bigImg.style.left = -bigLeft + 'px'; 111 bigImg.style.top = -bigTop + 'px'; 112 } 113 } 114 </script> 115 </head> 116 <body> 117 <div id="main"> 118 <div id="small"> 119 <img src="img/ktm_small.jpg" alt=""> 120 <div id="mark"></div> 121 </div> 122 <div id="big"> 123 <img src="img/ktm_big.jpg" alt=""> 124 </div> 125 </div> 126 </body> 127 </html>