直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>放大镜</title>
<style>
.box{
position: relative;
}
#smallBox,#bigBox{
width: 400px;
height: 400px;
border: 1px solid #333;
}
#smallBox img{
width: 400px;
}
#bigBox{
overflow: hidden;
position: absolute;
left: 420px;
top: 0;
display: none;
}
#mask{
width: 200px;
height: 200px;
background-color: rgba(23, 7, 255, .4);
position: absolute;
top: 0;
left: 0;
display: none;
}
#smallBox{
position: relative;
}
</style>
</head>
<body>
<div class="box">
<!-- 小图 400*400 -->
<div id="smallBox">
<img src="./images/phone.jpg" alt="">
<!-- 遮罩层 -->
<div id="mask"></div>
</div>
<!-- 大图 800*800 -->
<div id="bigBox">
<img src="./images/phone.jpg" alt="" id="bigImg">
</div>
</div>
</body>
<script>
var smallBox = document.getElementById('smallBox');
var bigImg = document.getElementById('bigImg');
var mask = document.getElementById('mask');
var bigBox = document.getElementById('bigBox');
smallBox.onmousemove = function(e){
// 获取鼠标相对于 smallBox 左上角的坐标
var x = e.clientX - this.offsetLeft;
var y = e.clientY - this.offsetTop;
console.log(x,y);
if (x <= 100) {
x = 100;
}
if (x >= 300) {
x = 300;
}
if (y <= 100) {
y = 100;
}
if (y >= 300) {
y = 300;
}
// 遮罩层的位置
// 遮罩层的大小 = 鼠标在小盒子中不能移动的距离
mask.style.left = x - 100 + 'px';
mask.style.top = y - 100 + 'px';
// 大图:小图 2:1
bigImg.style.marginLeft = -x*2 + 100*2 +'px';
bigImg.style.marginTop = -y*2 + 100*2 + 'px';
}
// 鼠标移入 smallBox
smallBox.onmouseenter = function(){
// mask bigBox 显示
mask.style.display = 'block';
bigBox.style.display = 'block';
}
// 鼠标移出 smallBox
smallBox.onmouseleave = function(){
// mask bigBox 隐藏
mask.style.display = 'none';
bigBox.style.display = 'none';
}
</script>
</html>