放大镜

重点

1.鼠标事件
2.offset系列,client系列
3.数据

效果


素材


案例代码

Css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
*{
padding: 0;
margin: 0;
}
/* 框架 */
.wrap {
position: relative;
margin: 100px;
}

/* 小图框 */
.min {
position: relative;
width: 350px;
}
/* 小图图片 */
.min img {
width: 100%;
}
/* 遮罩 */
.min_wrap {
width: 175px;
height: 175px;
position: absolute;
top: 0;
left: 0;
cursor: move;
background-color: rgba(255,255,0,.4);
display: none;
}

/* 大图框 */
.max_wrap {
border: 1px solid #000;
position: absolute;
top: 1px;
left: 370px;
width: 400px;
height: 400px;
overflow: hidden;
display: none;
}
.max_wrap img {
position: absolute;
width: 800px;
}

Html

1
2
3
4
5
6
7
8
9
10
11
<div class="wrap">
<div class="min">
<img src="images/small.png" alt="">
<div class="min_wrap">

</div>
</div>
<div class="max_wrap">
<img src="images/big.jpg" alt="">
</div>
</div>

Js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
window.onload = () => {
let wrap = document.querySelector(".wrap");
let min = document.querySelector(".min");
let min_img = document.querySelector(".min img");
let min_wrap = document.querySelector(".min_wrap");
let max_img = document.querySelector(".max_wrap img");
let max_wrap = document.querySelector(".max_wrap");

// 鼠标进入框架显示遮罩和大图
min.onmouseenter = () => {
min_wrap.style.display = "block";
max_wrap.style.display = "block";
}
// 鼠标离开框架隐藏遮罩和大图
min.onmouseleave = () => {
min_wrap.style.display = "none";
max_wrap.style.display = "none";
}

// 鼠标移动事件
wrap.onmousemove = e => {
// 兼容写法
var e = e || window.event;
// 获取鼠标的移动位置
let x = e.clientX - wrap.offsetLeft - min_wrap.offsetWidth / 2;
let y = e.clientY - wrap.offsetTop - min_wrap.offsetHeight / 2;

// 判断不要超出框架
if (x < 0) {
x = 0;
} else if (x > min_img.offsetWidth - min_wrap.offsetWidth) {
x = min_img.offsetWidth - min_wrap.offsetWidth;
}

if (y < 0) {
y = 0;
} else if (y > min_img.offsetHeight - min_wrap.offsetHeight) {
y = min_img.offsetHeight - min_wrap.offsetHeight;
}

// 设置遮罩移动
min_wrap.style.left = x + "px";
min_wrap.style.top = y + "px";

// 计算比例
let bl = (max_img.offsetWidth-max_wrap.offsetWidth) / (min.offsetWidth - min_wrap.offsetWidth);

// 设置大图移动
max_img.style.left = -x * bl + "px";
max_img.style.top = -y * bl + "px";
}
}
-------------本文结束感谢您的阅读-------------
0%