<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>放大镜效果</title>
<style>
*{margin:0;padding: 0;}
#box{
width:700px;
height:300px;
background:greenyellow;
margin:50px auto;
}
#box1{
width:300px;
height:300px;
background: #FFA500;
float: left;
position: relative;
}
#box2{
width:300px;
height:300px;
background: #FFA500;
overflow: hidden;
float: right;
position: relative;
}
#dv{
width: 100px;
height:100px;
background:#FFA500;
position: absolute;
left:0;
top:0;
opacity: 0.5;
}
#imgs{
position: absolute;
left:0px;
top:0;
}
</style>
</head>
<body>
<div id="box">
<div id="box1"><img src="images/0.jpg" width="300px"/><div id="dv"></div></div>
<div id="box2"><img src="images/0.jpg" width="900px" id="imgs"/></div>
</div>
<script src="script.js"></script>
</body>
</html>
var box1 = document.getElementById("box1"),
dv = document.getElementById("dv"),
imgs = document.getElementById("imgs");
box1.onmousemove = function(e){
var e = window.event || e;
var left = e.clientX - box1.offsetLeft - dv.offsetWidth/2;
var top = e.clientY - box1.offsetTop - dv.offsetHeight/2;
if(e.clientX <= box1.offsetLeft + dv.offsetWidth/2 ){
left = 0 ;
}
if(e.clientY <= box1.offsetTop+ dv.offsetHeight/2){
top = 0;
}
if(e.clientX >= box1.offsetLeft+box1.offsetWidth-dv.offsetWidth/2){
left = box1.offsetWidth-dv.offsetWidth;
}
if(e.clientY >= box1.offsetTop+box1.offsetHeight-dv.offsetHeight/2){
top = box1.offsetHeight-dv.offsetHeight;
}
dv.style.left = left +"px";
dv.style.top = top +"px";
imgs.style.left = -left*3+"px";
imgs.style.top = -top*3+"px";
}