一个简单的放大镜demo
作者:互联网
html部分:
<div class="web">
<div class="goodsBox">
<img src="./small.jpg" alt="" />
<div class="mask"></div>
</div>
<div class="zoomBox">
<img src="./big.jpg" alt="">
</div>
</div>
css部分:
@charset "utf-8";
* {
margin: 0;
padding: 0;
text-decoration: none;
list-style: none;
}
.web {
padding: 50px;
}
.goodsBox {
width: 350px;
height: 350px;
overflow: hidden;
position: relative;
/* 鼠标移入变化 */
cursor: move;
}
.goodsBox>img {
width: 100%;
}
.mask {
display: none;
position: absolute;
width: 200px;
height: 200px;
background-color: rgba(255, 255, 0, 0.3);
top: 0;
left: 0;
/* 使得元素节点忽略事件触发 事件穿透 */
pointer-events: none;
}
.zoomBox {
position: absolute;
top: 0;
left: 400px;
width: 457px;
height: 457px;
overflow: hidden;
display: none;
}
.zoomBox img {
position: absolute;
top: 0;
left: 0;
}
js部分:
const goodsBoxNode = document.querySelector(".goodsBox");
const maskNode = document.querySelector(".mask");
const bigImg = document.querySelector(".zoomBox img");
const bigBox = document.querySelector(".zoomBox");
// 商品图片盒子高度
const goodsBoxHeight = goodsBoxNode.clientHeight;
// 商品图片盒子宽度
const goodsBoxWidth = goodsBoxNode.clientWidth;
// 遮罩层盒子高度
let maskHeight = 0;
// 遮罩层盒子宽度
let maskWidth = 0;
// 鼠标Y轴
let mouseY;
// 鼠标X轴
let mouseX;
// 鼠标在商品图片框中移动事件
goodsBoxNode.addEventListener("mousemove", (e) => {
mouseX = e.layerX - maskWidth / 2;
console.log(e.layerX);
// console.log(maskWidth);
if (mouseX < 0) {
mouseX = 0;
}
if (mouseX > goodsBoxWidth - maskWidth) {
mouseX = goodsBoxWidth - maskWidth;
}
maskNode.style.left = `${mouseX}px`;
bigImg.style.left = `-${mouseX * (bigImg.clientWidth / goodsBoxWidth)}px`;
mouseY = e.layerY - maskHeight / 2;
if (mouseY < 0) {
mouseY = 0;
}
if (mouseY > goodsBoxHeight - maskHeight) {
mouseY = goodsBoxHeight - maskHeight;
}
maskNode.style.top = `${mouseY}px`;
bigImg.style.top = `-${mouseY * (bigImg.clientHeight / goodsBoxHeight)}px`;
});
// 鼠标移入遮罩及放大图片出现
goodsBoxNode.addEventListener("mouseenter", () => {
maskNode.style.display = "block";
maskWidth = 200;
maskHeight = 200;
bigBox.style.display = "block";
});
// 鼠标移出遮罩及放大图片消失
goodsBoxNode.addEventListener("mouseleave", () => {
maskNode.style.display = "none";
bigBox.style.display = "none";
});
参考:https://blog.csdn.net/learner_boy/article/details/72190462
标签:style,const,放大镜,demo,none,mouseY,mouseX,简单,display 来源: https://www.cnblogs.com/echo42/p/15883806.html