本文实例为大家分享了javascript实现放大镜特效的具体代码,供大家参考,具体内容如下
我们在逛pc端商城时,鼠标放到商品上经常会看到一个类似放大镜效果的蒙层,
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
<!DOCTYPE html>
< html >
< head >
< meta charset = "UTF-8" >
< title ></ title >
< style type = "text/css" >
* {
margin: 0px;
padding: 0px;
}
#min {
width: 350px;
height: 350px;
border: 1px solid #ccc;
position: absolute;
left: 50px;
top: 50px;
}
#min img {
width: 350px;
height: 350px;
}
#max {
width: 500px;
height: 500px;
position: absolute;
left: 500px;
top: 50px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
#max img {
position: absolute;
left: 0;
top: 0;
}
#mask {
width: 200px;
height: 200px;
background: rgba(255, 0, 0, 0.5);
position: absolute;
left: 0px;
top: 0px;
cursor: pointer;
display: none;
}
</ style >
</ head >
< body >
< div id = "min" >
< img src = "img/min.jpg" alt = "" />
< div id = "mask" ></ div >
</ div >
< div id = "max" >
< img src = "img/max.jpg" id = "maxImg" />
</ div >
< script type = "text/javascript" >
// 1.鼠标经过小盒子,遮罩层出现,大盒子出现
// 2.遮罩层跟随鼠标移动
// 3.遮罩层移动,大盒子里的图片反方向移动
var oMin = document.getElementById('min');
var oMax = document.getElementById('max');
var oMask = document.getElementById('mask');
var oMaxImg = document.getElementById('maxImg');
oMin.onmousemove = function(e) {
// 1.鼠标经过小盒子,遮罩层和大盒子出现
oMask.style.display = 'block';
oMax.style.display = 'block';
// 2.拿到鼠标在小盒子上的坐标
var minX = e.clientX - oMin.offsetLeft;
var minY = e.clientY - oMin.offsetTop;
// 3.将鼠标放置在遮罩层的中间
minX = minX - oMask.offsetWidth / 2;
minY = minY - oMask.offsetHeight / 2;
// 4.遮罩层可以移动的最大距离
var maxWidth = oMin.offsetWidth - oMask.offsetWidth;
var maxHeight = oMin.offsetHeight - oMask.offsetHeight;
// 限定遮罩层的位置
if (minX > maxWidth) {
minX = maxWidth;
} else if (minX <= 0) {
minX = 0;
}
if (minY > maxHeight) {
minY = maxHeight;
} else if (minY <= 0) {
minY = 0;
}
// 设定遮罩层的偏移
oMask.style.left = minX + 'px';
oMask.style.top = minY + 'px';
// 大图片移动的距离=遮罩层移动的距离/遮罩层可以移动的最大距离*大图片最大移动距离
var ratioX = minX / maxWidth;
var ratioY = minY / maxHeight;
// 计算出大图片的移动距离
oMaxImg.style.left = -ratioX * (oMaxImg.offsetWidth - oMax.offsetWidth) + 'px';
oMaxImg.style.top = -ratioY * (oMaxImg.offsetHeight - oMax.offsetHeight) + 'px';
};
// 鼠标移开,遮罩层和大盒子消失
oMin.onmouseout = function() {
oMask.style.display = 'none';
oMax.style.display = 'none';
}
</ script >
</ body >
</ html >
|
效果图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_45334111/article/details/110483842