效果
需求
| 需求 | |
|---|---|
| 1.鼠标移入显示遮罩和旁边的放大镜;移出消失 | onmouseover移入;onmousemove鼠标移动;onmouseout/leave移出 |
| 2.鼠标移动遮罩也移动 | 用到了事件e=window.event |
事件 e||window.event_webkui的博客-CSDN博客
布局
<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 200px;
height: 200px;
margin: 100px;
position: relative;
}
.big {
width: 200px;
height: 200px;
position: absolute;
top: 0;
left: 200px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
#mask {
width: 50px;
height: 50px;
background: yellow;
opacity: 0.5;
position: absolute;
top: 0;
left: 0;
display: none;
pointer-events: none;
/* 鼠标事件穿透——可以让移动时不会出现抖动 */
}
#smallBox {
position: relative;
}
.smallBoxImg{
width:150px
}
#bigBox>img {
/*让里面的图片进行一个移动*/
position: absolute;
}
</style>
</head>
<body>
<div id="box">
<div id="smallBox">
<img src="2.jpg"alt="" class="smallBoxImg">
<div id="mask"></div>
</div>
<div class="big" id="bigBox">
<img id="bigImg" src="2.jpg" alt="">
</div>
</div>
<script>
//onload页面加载完毕后执行(浏览器常用事件)
window.onload = function () {
//获取元素
let smallBox = document.querySelector('#smallBox'); //小盒子
let mask = document.querySelector('#mask'); //遮罩
let bigBox = document.querySelector('#bigBox'); //大盒子
let bigImg = document.querySelector('#bigImg'); //大图片
let box = document.querySelector('#box'); //获取最外面box的offsetLeft到body的距离
let smallBoxImg = document.querySelector('.smallBoxImg')
smallBox.onmouseover = function () {// 鼠标移入显出
bigBox.style.display = 'block';
mask.style.display = 'block';
bigImg.style.transform = 'scale(2.4)';//放大倍数2.4
}
smallBox.onmouseout = function () {// 鼠标移出消失
bigBox.style.display = 'none';
mask.style.display = 'none';
}
smallBox.onmousemove = function (e) {//鼠标移动触发
e = window.event;
//a.遮罩mask跟随鼠标移动
let x = e.pageX - box.offsetLeft;
let y = e.pageY - box.offsetTop;
//b.鼠标在mask中心位置
mask.style.left = e.offsetX - 20 + 'px';
mask.style.top = e.offsetY - 20 + 'px';
//bigImg相应移动
bigImg.style.left = -x * bigBox.offsetWidth / mask.offsetWidth + 170 + 'px';
bigImg.style.top = -y * bigBox.offsetHeight / mask.offsetHeight + 170 + 'px';
}
}
</script>
</body>
</html>