先分析下大致原理,放大原理实际上是一张正常图片,再加上一张放大n倍图片,根据鼠标在正常图片上的位置,再将位置乘n倍,定位到放大图片,显示。 先来看看效果
<!DOCTYPE html>
<html lang ="en" >
<head > <meta charset ="UTF-8" > <title > Document</title > <style > *{padding : 0 px ;margin : 0 px ;} .box {width : 400 px ;height : 300 px ;border :1 px solid #ccc ;cursor : crosshair ;position : relative ;} .box img {width : 400 px ;height : 300 px ;} #zoom {position : absolute ;width : 100 px ;height : 100 px ;background : red ;opacity : 0.5 ;filter :alpha(opacity=50 ) ;left : 0 px ;top : 0 px ;display : none ;} .bigbox img {width : 1600 px ;height : 1200 px ;} .bigbox {width : 400 px ;height : 300 px ;overflow : hidden ;position : absolute ;display : block ;background-color : #4ae75e ;} </style >
</head >
<body >
<div class ="box" id ="box" > <img src ="images/11.jpg" alt ="" > <div id ="zoom" > </div >
</div >
<div class ="bigbox" id ="bigbox" > <img src ="images/11.jpg " alt ="im" >
</div >
<div > 横坐标:<span id ="ab" > </span > 纵坐标:<span id ="bc" > </span > zoom横坐标:<span id ="cd" > </span > zoom纵坐标:<span id ="dc" > </span >
</div >
<script > var box=document.getElementById('box' );var bigbox=document.getElementById('bigbox' );box.onmousemove=function (en) {var e=en||window.event;bigbox.style.display="block" ;bigbox.style.left=box.offsetLeft+box.offsetWidth+5 +'px' ;bigbox.style.top=box.offsetTop+'px' ;var x=e.clientX-box.offsetLeft;var y=e.clientY-box.offsetTop;zoom.style.display="block" ;ab.innerHTML=x;bc.innerHTML=y;var left=Math .min(Math .max(x-50 ,0 ),300 );var top=Math .min(Math .max(y-50 ,0 ),200 );cd.innerHTML=left;dc.innerHTML=top;zoom.style.left=left+'px' ;zoom.style.top=top+'px' ;bigbox.scrollLeft=left*4 ;bigbox.scrollTop=top*4 ;}box.onmouseout=function () { bigbox.style.display="none" ;zoom.style.display="none" ;}
</script >
</body >
</html >
解释两行代码 var left=Math.min(Math.max(x-50,0),300); var top=Math.min(Math.max(y-50,0),200); 首先解释下300,200是因为box div大小为400,300,zoom的width,height都是100,至于理解这两行代码最好的方法是将鼠标放在左上角和右下角观察值的变动。