html部分
<main class="main">
<!-- 左侧大图 -->
<div class="left-imgs" id="leftImgs">
<div class="mask" id="mask"></div>
<img src="https://oss.3c2p.com/goodsImages/big_85951650946828556.jpg" />
</div>
<!-- 右侧大图 -->
<div class="right-imgs" id="bigBox">
<img
id="bigImgs"
src="https://oss.3c2p.com/goodsImages/big_85951650946828556.jpg"
/>
</div>
</main>
css部分
<style>
.main {
display: flex;
}
.left-imgs {
width: 400px;
height: 400px;
position: relative;
border: 1px solid #ddd;
}
.left-imgs > img {
width: 100%;
height: 100%;
font-size: 0;
}
.mask {
position: absolute;
width: 150px;
height: 150px;
background-color: #000;
opacity: 0.3;
display: none;
}
.right-imgs {
width: 400px;
height: 400px;
overflow: hidden;
font-size: 0;
margin: 0;
padding: 0;
display: none;
position: relative;
}
.right-imgs > img {
position: absolute;
top: 0;
left: 0;
}
</style>
javascript部分
<script>
// 左侧盒子
const leftImgs = document.querySelector('#leftImgs');
// 阴影盒子
const mask = document.querySelector('#mask');
// 大图片盒子
const bigBox = document.querySelector('#bigBox');
// 大图片
const bigImgs = document.querySelector('#bigImgs');
// 左侧盒子鼠标移入显示阴影盒子和右侧大盒子
leftImgs.onmouseover = function (e) {
mask.style.display = 'block';
bigBox.style.display = 'block';
};
// 阴影盒子移动
leftImgs.onmousemove = function (e) {
// 当前鼠标位置 - 左侧盒子距离左侧浏览器偏移量 - 阴影盒子宽度一半
let x = e.clientX - leftImgs.offsetLeft - mask.offsetWidth / 2;
let y = e.clientY - leftImgs.offsetTop - mask.offsetHeight / 2;
// 阴影盒子移动位置X轴限定
if (x < 0) {
x = 0;
} else if (x > leftImgs.offsetWidth - mask.offsetWidth) {
x = leftImgs.offsetWidth - mask.offsetWidth;
}
// 阴影盒子移动位置Y轴限定
if (y < 0) {
y = 0;
} else if (y > leftImgs.offsetHeight - mask.offsetHeight) {
y = leftImgs.offsetHeight - mask.offsetHeight;
}
// 阴影盒子移动
mask.style.left = x + 'px';
mask.style.top = y + 'px';
// 大图片图片区域移动
bigImgs.style.left = -x * 2 + 'px';
bigImgs.style.top = -y * 2 + 'px';
};
leftImgs.onmouseout = function (e) {
mask.style.display = 'none';
bigBox.style.display = 'none';
};
</script>