<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link type="text/css" rel="stylesheet" href="../css/reset.css"/>
<style>
#box{
margin: 100px;
position: relative;
}
.small{
width: 450px;
height: 450px;
border: 1px solid #eeeeee;
position: relative;
}
.small{
cursor: move;
}
.small span{
width: 200px;
height: 200px;
position: absolute;
left: 0;
top: 0;
/*background-color:#eeeeee;*/
background: rgba(255,255,0,0.5);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#7fFFFF00,endColorstr=#7fFFFF00);
display: none;
}
.big{
display: none;
width: 400px;
height: 500px;
overflow: hidden;
position: absolute;
left: 460px;
top: 0;
border: 1px solid #eeeeee;
}
</style>
</head>
<body>
<div id="box" class="box">
<div class="small">
<img src="../img6/1.jpg"/>
<span class="bg" id="bg"></span>
</div>
<div class="big" id="big">
<img src="../img6/2.jpg"/>
</div>
</div>
<script >
function queryId(id) {
return document.getElementById(id);
}
//查找最外层的box
var box = queryId("box");
//小图div
var small = box.children[0];
//遮挡层
var bg = queryId("bg");
//大图div
var big = queryId("big");
//大图片
var bigImg = big.children[0];
//遮挡层移动
//ie8 如果使用bg移动,有问题,采用document
document.onmousemove = function (ev) {
//移动的距离
var clientX = window.event?window.event.clientX:ev.clientX;
var clientY = window.event?window.event.clientY:ev.clientY;
//让鼠标在遮挡层中间
clientX = clientX-bg.offsetWidth/2;
clientY = clientY-bg.offsetHeight/2;
//减去margin的距离,使鼠标在遮挡层左上方
clientX = clientX- 100;
clientY = clientY- 100;
//控制遮挡层只能在小图里面移动
clientX = clientX<0?0:clientX;//小于0 就给0
//大于可移动距离给最大可移动距离
clientX = clientX>small.offsetWidth-bg.offsetWidth?small.offsetWidth-bg.offsetWidth:clientX;
clientY = clientY<0?0:clientY;
clientY = clientY>small.offsetHeight-bg.offsetHeight?small.offsetHeight-bg.offsetHeight:clientY;
bg.style.left = clientX+"px";
bg.style.top = clientY+"px";
//遮挡层的移动距离/大图的移动距离 = 遮挡层最大移动距离/大图最大移动距离 a/b = c/d
//大图的移动距离 = 遮挡层的移动距离*大图最大移动距离/遮挡层最大移动距离 b = a*d/c
//大图横向移动距离
var maxX = clientX*(bigImg.offsetWidth-big.offsetWidth)/(small.offsetHeight-bg.offsetHeight);
//大图纵向移动距离
var maxY = clientY*(bigImg.offsetHeight-big.offsetHeight)/(small.offsetHeight-bg.offsetHeight);
//大图片移动除了脱标还有margin
bigImg.style.marginLeft = -maxX+"px";
bigImg.style.marginTop = -maxY+"px";
};
//鼠标进入显示遮挡层和大图
box.onmouseover = function () {
bg .style.display = "inline-block";
big.style.display = "block";
};
box.onmouseout = function () {
bg .style.display = "none";
big.style.display = "none";
};
</script>
</body>
</html>
实现效果: