<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></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;
}
.box img {
vertical-align: top;
}
#bigBox img {
position: absolute;
}
</style>
</head>
<body>
<div class="box" id="box">
<div id="smallBox" class="small">
<img src="images/001.jpg" width="350" alt=""/>
<div id="mask" class="mask"></div>
</div>
<div id="bigBox" class="big">
<img id="bigImg" src="images/0001.jpg" width="800" alt=""/>
</div>
</div>
<script>
//找人
var box = document.getElementById("box");
var smallBox = document.getElementById("smallBox");
var mask = document.getElementById("mask");
var bigBox = document.getElementById("bigBox");
var bigImg = document.getElementById("bigImg");
//1.鼠标经过盒子 显示遮罩和大盒子
smallBox.onmouseover = function () {
mask.style.display = "block";
bigBox.style.display = "block";
};
smallBox.onmouseout = function () {
mask.style.display = "none";
bigBox.style.display = "none";
};
//2.鼠标在smallBox上移动的时候 让mask跟着鼠标移动
smallBox.onmousemove = function (event) {
var event = event || window.event;
var pageX = event.pageX || event.clientX + document.documentElement.scrollLeft;
var pageY = event.pageY || event.clientY + document.documentElement.scrollTop;
//计算鼠标在小盒子中的座标
var boxX = pageX - box.offsetLeft;
var boxY = pageY - box.offsetTop;
//计算遮罩的位置
var maskX = boxX - mask.offsetWidth / 2;
var maskY = boxY - mask.offsetHeight / 2;
//3.限定遮罩的运动范围
if (maskX < 0) {
maskX = 0;
}
if (maskX > smallBox.offsetWidth - mask.offsetWidth) {
maskX = smallBox.offsetWidth - mask.offsetWidth;
}
if (maskY < 0) {
maskY = 0;
}
if (maskY > smallBox.offsetHeight - mask.offsetHeight) {
maskY = smallBox.offsetHeight - mask.offsetHeight;
}
console.log(maskX + "---" + maskY);
//设置遮罩的位置
mask.style.left = maskX + "px";
mask.style.top = maskY + "px";
//4.按照比例关系 设置大图的位置
//大图现在应该在的位置/遮罩现在在的位置=大图移动的总距离/遮罩移动的总距离
//大图现在应该在的位置=大图移动的总距离/遮罩移动的总距离*遮罩现在在的位置
//大图现在应该在的位置=rate*遮罩现在在的位置
//遮罩移动的总距离= 小盒子的宽度-遮罩的宽度
var maskToMove = smallBox.offsetWidth - mask.offsetWidth;
//大图移动的总距离=大图片的宽度-大盒子的宽度
var bigImgToMove = bigImg.offsetWidth - bigBox.offsetWidth;
//rate = 大图移动的总距离/遮罩移动的总距离
var rate = bigImgToMove / maskToMove;
//设置大图的位置
//大图现在应该在的位置=rate*遮罩现在在的位置
bigImg.style.left = -rate * maskX + "px";//注意方向相反
bigImg.style.top = -rate * maskY + "px";//注意方向相反
};
</script>
</body>
</html>