<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大镜</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box1{
width: 400px;
height: 400px;
position: relative;
}
#box1 img{
width: 400px;
height: 400px;
}
#box2{
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 410px;
overflow: hidden;
border: 1px solid gray;
display: none;
}
#fdj{
position: absolute;
top: 0;
left: 0;
background: rgba(255,255,255,.4);
border: 1px solid gray;
cursor: move;
display: none;
}
</style>
</head>
<body>
<div id="box1">
<img src="1234.jpg" alt="" />
<span id="fdj"></span>
</div>
<div id="box2">
<img id="big_img" src="1234.jpg" alt="" />
</div>
<script>
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
var fdj = document.getElementById('fdj');
var big_img = document.getElementById('big_img');
var scale = 2;
fdj.style.width = parseInt(box1.offsetWidth / scale) + 'px';
fdj.style.height = parseInt(box1.offsetHeight / scale) + 'px';
big_img.style.width = box1.offsetWidth * 2 + 'px';
big_img.style.height = box1.offsetHeight * 2 + 'px';
box1.onmouseover = function(){
fdj.style.display = 'block';
box2.style.display = 'block';
}
box1.onmouseout = function(){
fdj.style.display = 'none';
box2.style.display = 'none';
}
box1.onmousemove = function(ev){
var e = ev || event;
var x = e.clientX - fdj.offsetWidth / 2;
var y = e.clientY - fdj.offsetHeight / 2;
if(x < 0){
x = 0;
}
if(x > box1.offsetWidth - fdj.offsetWidth){
x = box1.offsetWidth - fdj.offsetWidth;
}
if(y < 0){
y = 0;
}
if(y > box1.offsetHeight - fdj.offsetHeight){
y = box1.offsetHeight - fdj.offsetHeight;
}
fdj.style.left = x + 'px';
fdj.style.top = y + 'px';
var m_left = x * scale;
var m_top = y * scale;
big_img.style.marginLeft = -m_left + 'px';
big_img.style.marginTop = -m_top + 'px';
}
</script>
</body>
</html>