<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
#smallbox {
width: 430px;
height: 430px;
position: relative;
top: 50px;
margin-left: 50px;
background-image: url('./small.jpg');
background-size: cover;
float: left;
}
#bigbox {
width: 430px;
height: 430px;
position: relative;
float: left;
margin-left: 50px;
margin-top: 50px;
overflow: hidden;
display: none;
}
#big {
position: absolute;
left: 0;
top: 0;
}
#move {
width: 215px;
height: 215px;
background-color: rgba(0, 0, 0, .4);
left: 0;
top: 0;
display: none;
overflow: hidden;
position: absolute;
}
#show {
width: 430px;
height: 430px;
background-color: transparent;
z-index: 10;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
}
</style>
<body>
<!-- 小图 -->
<div id="smallbox">
<!-- 蒙版 -->
<div id="show"></div>
<!-- 移动的小方块块 -->
<div id="move"> </div>
</div>
<!-- 大图 -->
<div id="bigbox">
<img src="./big.jpg" alt="" id="big">
</div>
</body>
</html>
<script>
//获取网页中元素
var smallbox_ = document.getElementById('smallbox');
var bigbox_ = document.getElementById('bigbox');
var move_ = document.getElementById('move');
var img_ = document.getElementById('big');
var show_ = document.getElementById('show');
//添加鼠标移入事件监听
show_.addEventListener('mousemove', function (e) {
//鼠标滑入小滑块和大图显示
move_.style.display = 'block';
bigbox_.style.display = 'block';
var e = e || window.event;
//获取鼠标位置
var mousex = e.offsetX;
var mousey = e.offsetY;
//console.log(mousex, mousey);
//小滑块位置随鼠标移动,并将鼠标定位在滑块中间位置
move_.style.left = Math.floor(mousex - move_.offsetWidth / 2) + 'px';
move_.style.top = Math.floor(mousey - move_.offsetHeight / 2) + 'px';
/* move_.style.left = mousex + 'px';
move_.style.top = mousey + 'px'; */
//小滑块四边定位
var moleft = move_.style.left;
var motop = move_.style.top;
console.log(moleft, motop);
//允许滑动向右 想下的距离
var maxRight = smallbox_.offsetWidth - move_.offsetWidth;
var maxBottom = smallbox_.offsetHeight - move_.offsetHeight;
console.log(maxRight, maxBottom);
//左边
//move_.style.left = parseInt(move_.style.left) < 0 ? 0 : moleft;
if (parseInt(moleft) < 0) {
move_.style.left = 0;
} else {
move_.style.left = moleft;
}
//上边
if (parseInt(motop) < 0) {
move_.style.top = 0;
} else {
move_.style.top = motop;
}
//右边
if (parseInt(moleft) > maxRight) {
move_.style.left = maxRight + 'px';
} else {
move_.style.left = move_.style.left;
}
//下边
if (parseInt(motop) > maxBottom) {
move_.style.top = maxBottom + 'px';
} else {
move_.style.top = move_.style.top;
}
//滑块与大图片做联动 大图小图比例2:1 所以乘以-2
img_.style.left = parseInt(moleft) * -2 + 'px';
img_.style.top = parseInt(motop) * -2 + 'px';
})
//添加鼠标移出事件监听
show_.addEventListener('mouseout', function () {
move_.style.display = 'none';
bigbox_.style.display = 'none';
})
</script>