需求分析
- 1.小图片鼠标移入时:出现遮罩层,并将遮罩部分放大在右边显示
- 2.小图片鼠标移动时:遮罩层与大图片相应移动
- 2.1:鼠标在遮罩层中心位置
- 2.2:遮罩层边界检测,遮罩层不能超出图片范围
- 2.3:遮罩层与大图片相应移动 假如 遮罩层大小50px 50px 大图片100px 100px,那么每当遮罩层鼠标移动1px,大图片应该移动2px。(100/50)
- 3.小图片鼠标移出时:遮罩层与大图片隐藏
<!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>事件对象 - 案例 - 放大镜</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big {
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.mask {
width: 175px;
height: 175px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.small {
position: relative;
}
.box img {
vertical-align: top;
}
#bigBox > img {
position: absolute;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="small">
<img src="images/001.jpg" width="350" alt="" />
<div class="mask"></div>
</div>
<div class="big" id="bigBox">
<img id="bigImg" src="images/0001.jpg" width="800" alt="" />
</div>
</div>
</body>
<script>
const box = document.querySelector("#box");
const small = box.firstElementChild;
const mask = small.lastElementChild;
const bigBox = box.lastElementChild;
const bigImg = bigBox.firstElementChild;
console.log(box, small, mask, bigBox, bigImg);
small.onmouseover = function (e) {
e = e || window.event;
bigBox.style.display = "block";
mask.style.display = "block";
};
small.onmouseout = function (e) {
e = e || window.event;
bigBox.style.display = "";
mask.style.display = "";
};
small.onmousemove = function (e) {
e = e || window.event;
let x = e.pageX;
let y = e.pageY;
console.log(x, y);
x -= box.offsetLeft;
y -= box.offsetTop;
x -= mask.offsetWidth / 2;
y -= mask.offsetHeight / 2;
if (x < 0) x = 0;
if (y < 0) y = 0;
let maxX = small.offsetWidth - mask.offsetWidth;
let maxY = small.offsetHeight - mask.offsetHeight;
if (x > maxX) x = maxX;
if (y > maxY) y = maxY;
mask.style.left = x + "px";
mask.style.top = y + "px";
let xc = (bigImg.offsetWidth - bigBox.offsetWidth) / maxX;
let yc = (bigImg.offsetHeight - bigBox.offsetHeight) / maxY;
bigImg.style.left = -x * xc + "px";
bigImg.style.top = -y * yc + "px";
};
</script>
</html>
|