原理:
图片放大的原理其实是一张正常的图片
加上放大n倍图片
步骤:
获取鼠标在原图片的位置
将位置乘以n倍,
定位到放大的图片显示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
padding: 0px;
margin: 0px;
}
.box{
width: 400px;
height: 300px;
border:1px solid #ccc;
cursor: crosshair;
position: relative;
}
.box img{
width: 400px;
height: 300px;
}
#zoom{
position: absolute;
width: 100px;
height: 100px;
background: red;
opacity: 0.5;
filter:alpha(opacity=50);
left: 0px;
top: 0px;
display: none;
}
.bigbox img{
width: 1600px;
height: 1200px;
}
.bigbox{
width: 400px;
height: 300px;
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.οnmοusemοve=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;
// 求zoom的位置
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.οnmοuseοut=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,至于理解这两行代码最好的方法是将鼠标放在左上角和右下角观察值的变动。