一、基本流程
- 创建左右盒子分别包含左右图片,左盒内含遮罩加图片,
右图与左图宽高比 等同于 右盒与遮罩的宽高比
- 应用事件: 鼠标移入事件(
onmouseover) 鼠标移入事件(onmouseout) 鼠标移动事件(onmousemove)
- 左边盒子移入时,显示右边盒子,显示右边图片
- 左边盒子移出时,隐藏右边盒子,隐藏右边图片
- 左边盒子移动时通过当前位置位于盒子的距离依据公式计算出对应比例,显示右图图片位置
二、代码注释详解
<!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;
box-sizing: border-box;
}
.box {
display: flex;
margin: 200px 0 0 200px;
}
.leftBox img {
width: 100%;
height: 100%;
border: 1px solid #ccc;
}
.rightBox {
width: 320px;
height: 320px;
overflow: hidden;
position: relative;
margin-left: 100px;
}
.rightBox img {
width: 800px;
height: 800px;
display: none;
position: absolute;
}
.leftBox {
position: relative;
width: 200px;
height: 200px;
}
.mask {
cursor: pointer;
width: 80px;
height: 80px;
background-color: rgba(0, 0, 255, 0.24);
display: none;
position: absolute;
top: 0;
left: 0;
}
</style>
<body>
<div class="box">
<div class="leftBox">
<img src="./imgs/素材.jpg" alt="" class="leftImg">
<div class="mask"></div>
</div>
<div class="rightBox">
<img src="./imgs/素材.jpg" alt="" class="rightImg">
</div>
</div>
</body>
<script>
document.querySelector(".leftBox").onmouseover = function () {
document.querySelector(".rightBox img").style.display = "block";
document.querySelector(".mask").style.display = "block";
}
document.querySelector(".leftBox").onmouseout = function () {
document.querySelector(".rightBox img").style.display = "none";
document.querySelector(".mask").style.display = "none";
}
let box = document.querySelector(".box")
let mask = document.querySelector(".mask")
let rightBox = document.querySelector(".rightBox")
let leftBox = document.querySelector(".leftBox")
document.querySelector(".leftBox").onmousemove = function (e) {
let x = (e.pageX - box.offsetLeft) - (mask.offsetWidth / 2);
let y = (e.pageY - box.offsetTop) - (mask.offsetHeight / 2);
x = x < 0 ? 0 : x;
x = x > (leftBox.offsetWidth - mask.offsetWidth) ? (leftBox.offsetWidth - mask.offsetWidth) : x;
y = y < 0 ? 0 : y;
y = y > (leftBox.offsetHeight - mask.offsetHeight) ? (leftBox.offsetHeight - mask.offsetHeight) : y;
mask.style.left = x + 'px'
mask.style.top = y + 'px'
document.querySelector(".rightBox img").style.top = -y * (rightBox.offsetHeight / mask.offsetHeight) + 'px'
document.querySelector(".rightBox img").style.left = -x * (rightBox.offsetWidth / mask.offsetWidth) + 'px'
}
</script>
</html>