<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: 0px;
left: 0px;
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>
//獲取需要的元素
var box = my$("box");
//獲取小圖的div
var small = box.children[0];
//遮擋層
var mask = small.children[1];
//獲取大圖的div
var big = box.children[1];
//獲取大圖
var bigImg = big.children[0];
//鼠標進入顯示遮擋層和大圖的div
box.onmouseover = function () {
mask.style.display = "block";
big.style.display = "block";
};
//鼠標離開隱藏遮擋層和大圖的div
box.onmouseout = function () {
mask.style.display = "none";
big.style.display = "none";
};
//鼠標的移動事件---鼠標是在小層上移動
small.onmousemove = function (e) {
//鼠標此時的可視區(qū)域的橫坐標和縱坐標
//主要是設(shè)置鼠標在遮擋層的中間顯示
var x = e.clientX - mask.offsetWidth / 2;
var y = e.clientY - mask.offsetHeight / 2;
//主要是margin的100px的問題
x = x - 100;
y = y - 100;
//橫坐標的最小值
x = x < 0 ? 0 : x;
//縱坐標的最小值
y = y < 0 ? 0 : y;
//橫坐標的最大值
x = x > small.offsetWidth - mask.offsetWidth ? small.offsetWidth - mask.offsetWidth : x;
//縱坐標的最大值
y = y > small.offsetHeight - mask.offsetHeight ? small.offsetHeight - mask.offsetHeight : y;
//為遮擋層的left和top賦值
mask.style.left = x + "px";
mask.style.top = y + "px";
//遮擋層的移動距離/大圖的移動距離=遮擋層的最大移動距離/大圖的最大移動距離
//大圖的移動距離=遮擋層的移動距離*大圖的最大移動距離/遮擋層的最大移動距離
//大圖的橫向的最大移動距離
var maxX = bigImg.offsetWidth - big.offsetWidth;
//大圖的縱向的最大移動距離
//var maxY = bigImg.offsetHeight - big.offsetHeight;
//大圖的橫向移動的坐標
var bigImgMoveX = x * maxX / (small.offsetWidth - mask.offsetWidth);
//大圖的縱向移動的坐標
var bigImgMoveY = y * maxX / (small.offsetWidth - mask.offsetWidth);
//設(shè)置圖片移動
bigImg.style.marginLeft = -bigImgMoveX + "px";
bigImg.style.marginTop = -bigImgMoveY + "px";
};