效果图 html代码
js代码
$(() => {
//透明遮罩弹出来时,会获得鼠标焦点,event.target也会指向mask元素,这会让事件处理变得繁琐
//为了避免这些麻烦,我们直接在最上层放一个透明元素,通过这个透明元素来处理鼠标事件
//这里我们用event.clientX和elem.clientLeft来判断相对距离,这样就不用考虑元素父子关系,定位方式等问题
let imageElem = $("#image")[0];
//鼠标移入时,显示遮罩和大图
$("#zone").mouseenter(event => {
$("#mask").show();
$("#image-big").show();
});
//鼠标移出时,隐藏遮罩和大图
$("#zone").mouseleave(event => {
$("#mask").hide();
$("#image-big").hide();
});
//鼠标移动时,更新遮罩位置和大图显示区域
$("#zone").mousemove(event => {
//限制遮罩范围
let x = event.clientX - imageElem.clientLeft - 50;
if (x < 0)
x = 0;
if (x > 100)
x = 100;
let y = event.clientY - imageElem.clientTop - 50;
if (y < 0)
y = 0;
if (y > 100)
y = 100;
//更新遮罩位置
$("#mask").css({
left: x,
top: y
});
//更新大图显示区域
$("#image-big").css({
backgroundPositionX: -4 * x,
backgroundPositionY: -4 * y,
});
});
});
css代码
* {
margin: 0;
padding: 0;
font-size: 0;
}
body {
background: yellow;
}
#parent {
width: 200px;
height: 200px;
position: relative;
}
#image {
width: 200px;
height: 200px;
background: url("item_medium.jpg");
border: 1px dodgerblue solid;
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
}
#image-big {
width: 400px;
height: 400px;
background: url("item_big.jpg");
background-size: 800px, 800px;
border: 1px red solid;
box-sizing: border-box;
position: absolute;
top: 50px;
left: 250px;
display: none;
}
#mask {
width: 100px;
height: 100px;
background: rgba(255, 0, 0, 0.2);
position: absolute;
top: 0;
left: 0;
display: none;
}
#zone {
width: 200px;
height: 200px;
position: absolute;
}