<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="智能社 - zhinengshe.com"> <meta name="copyright" content="智能社 - zhinengshe.com"> <title>智能社 - www.zhinengshe.com</title> <style> * { margin:0; padding:0; } .box { margin-left:100px; margin-top:50px; } #div1 { position:relative; float:left; 310px; height:310px; border:1px solid red; background:url(images/m1.jpg) no-repeat; } #div1 span { display:none; position:absolute; top:0; left:0; 100px; height:100px; background:yellow; opacity:0.6; filter:alpha(opacity:60); cursor:move;} #div2 { display:none; position:relative; float:left; overflow:hidden; 310px; height:310px; border:1px solid green; margin-left:20px;} #div2 img { position:absolute; top:0; left:0; } </style> <script> window.onload=function (){ var oDiv1=document.getElementById('div1'); var oDiv2=document.getElementById('div2'); var oSpan=oDiv1.children[0]; var oImg=oDiv2.children[0]; oDiv1.onmouseover=function(ev) { oDiv2.style.display='block'; oSpan.style.display='block'; show(ev); }; oDiv1.onmouseout=function (){ oDiv2.style.display='none'; oSpan.style.display='none'; }; oDiv1.onmousemove=function (ev){ show(ev); //onmousemove 鼠标移动时候触发,不要放太浪费性能的东西 }; function show(ev) { var oEvent=ev||event; var x=oEvent.clientX; var y=oEvent.clientY; var l=x-oDiv1.offsetLeft-oSpan.offsetWidth/2; var t=y-oDiv1.offsetTop-oSpan.offsetHeight/2; if (t<0) { t=0; } if (t>oDiv1.offsetHeight-oSpan.offsetHeight) { t=oDiv1.offsetHeight-oSpan.offsetHeight-2;//在ie6下回出现覆盖边框情况,保证在范围内 } if (l<0) { l=0; } if (l>oDiv1.offsetWidth-oSpan.offsetWidth) { l=oDiv1.offsetWidth-oSpan.offsetWidth-2;//在ie6下回出现覆盖边框情况,保证在范围内 } oSpan.style.left=l+'px'; oSpan.style.top=t+'px'; // 大img位置计算 oImg.style.left=-l/(oDiv1.offsetWidth-oSpan.offsetWidth)*(oImg.offsetWidth-oDiv2.offsetWidth)+'px'; oImg.style.top=-t/(oDiv1.offsetHeight-oSpan.offsetHeight)*(oImg.offsetHeight-oDiv2.offsetHeight)+'px'; }; }; </script> </head> <body> <div class="box"> <div id="div1"> <span></span> </div> <div id="div2"> <img src="images/b1.jpg" /> </div> </div> </body> </html>