样式如图
html部分
<div class=\”box\”>
<div class=\”pic\”>
<img src=\”1.jpeg\” alt=\”\”>
<div class=\”cover\”></div>
</div>
<div class=\”detail\”>
<img src=\”1.jpeg\” alt=\”\”>
</div>
</div>
css部分
*{
margin: 0;
padding: 0;
}
.box{
position: relative;
width: 400px;
height: 400px;
margin: 50px 0 0 100px;
}
.pic, .pic img{
width: 100%;
height: 100%;
}
.cover{
display: none;
background-image: url(ge.jpg);
width: 150px;
height: 150px;
position: absolute;
left: 0;
top: 0;
background-size: 3px;
opacity: 0.5;
}
.detail{
position: absolute;
left: 400px;
top: 0;
width: 400px;
height: 400px;
overflow: hidden;
}
.detail img{
/* width: 100%;
height: 100%; */
display: none;
position: absolute;
}
js部分
let pic = document.querySelector(\”.pic\”); //获取左侧盒子
let cover = document.querySelector(\”.cover\”); //获取遮罩层
let detail = document.querySelector(\”.detail\”); //获取右侧盒子
let detailImg = document.querySelector(\”.detail img\”); //获取右侧图片
// 鼠标进入左侧图片时显示遮罩层和右侧图片
pic.addEventListener(\”mouseenter\”,function(e){
cover.style.display = \”block\”;
detailImg.style.display = \”block\”;
});
// 鼠标离开左侧图片时遮罩层和右侧图片隐藏
pic.addEventListener(\”mouseleave\”,function(e){
cover.style.display = \”none\”;
detailImg.style.display = \”none\”;
});
// 鼠标在图片中移动事件监听
pic.addEventListener(\”mousemove\”,function(e){
// 获取鼠标坐标
let x = e.clientX;
let y = e.clientY;
// 左侧图片的坐标
let left = pic.getBoundingClientRect().left;
let top = pic.getBoundingClientRect().top;
// 遮罩层在图片上的偏移量
let cLeft = x – left – cover.offsetWidth/2;
let cTop = y – top – cover.offsetHeight/2;
// 判断临界值
// left 和top的最大值
let leftMax = pic.offsetWidth – cover.offsetWidth;
let topMax = pic.offsetHeight – cover.offsetHeight;
if(cLeft < 0){
cLeft = 0;
}
if(cLeft > leftMax){
cLeft = leftMax;
}
if(cTop < 0){
cTop = 0;
}
if(cTop>topMax){
cTop = topMax;
}
//设置遮罩层的位置
cover.style.left = cLeft + \”px\”;
cover.style.top = cTop + \”px\”;
// 显示放大的图片
// detailImg.left/detailImg.width -detail.width = cover.left/pic.width-cover.width;
let detailImgLeft = (detailImg.offsetWidth – detail.offsetWidth )*cLeft/(pic.offsetWidth-cover.offsetWidth);
let detailImgTop = (detailImg.offsetHeight – detail.offsetHeight )*cTop/(pic.offsetHeight-cover.offsetHeight);
// 设置右侧放大图片的位置
detailImg.style.left = \”-\” + detailImgLeft + \”px\”;
detailImg.style.top = \”-\” + detailImgTop + \”px\”;
});