<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>zhengfei</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big {
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.mask {
width: 175px;
height: 175px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.small {
position: relative;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="small"><!--小层-->
<img src="images/small.png" width="350" alt=""/>
<div class="mask"></div><!--遮挡层-->
</div><!--小图-->
<div class="big"><!--大层-->
<img src="images/big.jpg" width="800" alt=""/><!--大图-->
</div><!--大图-->
</div>
<!--导入外部的js文件-->
<script src="common.js"></script>
<script>
//获取需要的元素
var box = my$("box");
var small = box.children[0];
var mask = small.children[1];
var big = box.children[1];
//鼠标进入显示遮挡层和大图
box.onmouseover = function () {
mask.style.display = "block";
big.style.display = "block";
};
//鼠标离开隐藏遮挡层和大图
box.onmouseout = function () {
mask.style.display = "none";
big.style.display = "none";
};
//鼠标的移动事件(小层上移动)
small.onmousemove = function (e) {
//此时可视区域鼠标的横纵坐标
var x = e.clientX - mask.offsetWidth / 2;
var y = e.clientY - mask.offsetHeight / 2;
x = x - 100;
y = y - 100;
x = x > 0 ? x : 0;
x = x > small.offsetWidth - mask.offsetWidth ? small.offsetWidth - mask.offsetWidth : x;
y = y > 0 ? y : 0;
y = y > small.offsetHeight - mask.offsetHeight ? small.offsetHeight - mask.offsetHeight : y;
//为遮挡层的left top赋值
mask.style.left = x + "px";
mask.style.top = y + "px";
//遮挡层的移动距离:大图的移动距离====遮挡层的最大移动距离:大图的最大移动距离
//遮挡层的最大横向移动距离
var xMaskMax = small.offsetWidth - mask.offsetWidth;
//遮挡层的最大纵向移动距离
var yMaskMax = small.offsetHeight - mask.offsetHeight;
//大图的横向最大移动距离
var xBigMax = big.children[0].offsetWidth - big.offsetWidth;
//大图的纵向最大移动距离
var yBigMax = big.children[0].offsetHeight - big.offsetHeight;
big.children[0].style.marginLeft = -x * xBigMax / xMaskMax + "px";
big.children[0].style.marginTop = -y * yBigMax / yMaskMax + "px";
};
</script>
</body>
</html>
注:my$为封装的通过id获取元素函数
function my$(id) {
return document.getElementById(id);
};
移动大图时设置的不是left和top,而是marginLeft和marginTop
效果图: