<!doctype html> <html> <head> <meta charset="UTF-8"> <title>放大镜</title> <style> *{ padding:0; margin:0; } #box{ 400px; height:255px; border:1px solid #ac0; position:relative; } #smallBox{ 400px; height:255px; position:relative; } #mark{ position:absolute; 400px; height:255px; background:red; opacity:0; z-index:10; } #mirro{ display:none; position:absolute; 160px; height:160px; background:#fff; opacity:.5; } #bigBox{ 400px; height:255px; position:absolute; left:430px; overflow:hidden; top:0; display:none; border:1px solid #ac0; } #bigImg{ position:absolute; } </style> </head> <body> <div id="box"> <div id="smallBox"> <div id="mark"></div> <div id="mirro"></div> <img src="../img/small.jpg" id="smallImg"/> </div> <div id="bigBox"> <img src="../img/big.jpg" id="bigImg"/> </div> </div> </body> </html> <script> function $(id){ return document.getElementById(id); } window.onload=function(){ $("mark").onmouseover=function(){ $("mirro").style.display="block"; $("bigBox").style.display="block"; } $("mark").onmouseout=function(){ $("mirro").style.display="none"; $("bigBox").style.display="none"; } $("mark").onmousemove=function(e){ var e=event||window.event; var box=$("box"); var mark=$("mark"); var mirro=$("mirro"); var bigBox=$("bigBox"); var smallBox=$("smallBox"); var bigBoximg=$("bigImg"); var left=e.clientX-box.offsetLeft-smallBox.offsetLeft-mirro.offsetWidth/2; var top=e.clientY-box.offsetTop-smallBox.offsetTop-mirro.offsetHeight/2; //判断边界 if(left<0){ left=0; }else if(left>mark.offsetWidth-mirro.offsetWidth){ left=mark.offsetWidth-mirro.offsetWidth; } if(top<0){ top=0; }else if(top>mark.offsetHeight-mirro.offsetHeight){ top=mark.offsetHeight-mirro.offsetHeight; } $("mirro").style.top=top+"px"; $("mirro").style.left=left+"px"; var perX=left/(mark.offsetWidth-mirro.offsetWidth); var pery=top/(mark.offsetHeight-mirro.offsetHeight); bigBoximg.style.left=-perX*(bigBoximg.offsetWidth-bigBox.offsetWidth)+"px"; bigBoximg.style.top=-pery*(bigBoximg.offsetHeight-bigBox.offsetHeight)+"px"; } } </script>