图片放大镜效果实现

html代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div class="box" id="box">
<!--小层-->
<div class="small">
<img src="small.png" width="350" alt=""/>
<!--遮挡层-->
<div class="mask"></div>
</div>

<!--大层-->
<div class="big">
<!--大图-->
<img src="big.jpg" width="800" alt=""/>
</div>
</div>

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
.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: 0px;
left: 0px;
cursor: move;
display: none;
}
.small {
position: relative;
}

JavaScript代码

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
// 获取需要的元素
var box = document.getElementById("box");
// 获取小图的div
var small = box.children[0];
// 获取遮挡层
var mask = small.children[1];
// 获取大图的div
var big = box.children[1];
// 获取大图
var bigImg = big.children[0];

// 鼠标进入时显示遮挡层和大图
box.onmouseover = function () {
mask.style.display = "block";
big.style.display = "block";
};
// 鼠标离开时隐藏遮挡层和大图
box.onmouseout = function () {
mask.style.display = "none";
big.style.display = "none";
};

// 鼠标的移动事件---鼠标是在小层上移动
small.onmousemove = function (event) {
// 鼠标此时的可视区域的横坐标和纵坐标
// 设置鼠标在遮挡层的中间显示
// clientX表示鼠标离区域左边距离

var x = event.clientX - mask.offsetWidth / 2;
var y = event.clientY - mask.offsetHeight / 2;
// 解决margin100px造成的偏移问题
x = x - 100;
y = y - 100;
// 横坐标的最小值(左边界)
x = x < 0 ? 0 : x;
// 纵坐标的最小值(上边界)
y = y < 0 ? 0 : y;
// 横坐标的最大值(右边界)
x = x > small.offsetWidth - mask.offsetWidth ?
small.offsetWidth - mask.offsetWidth : x;
// 纵坐标的最大值(下边界)
y = y > small.offsetHeight - mask.offsetHeight ?
small.offsetHeight - mask.offsetHeight : y;
// 为遮挡层的left和top赋值
mask.style.left = x + "px";
mask.style.top = y + "px";

// 遮挡层的移动距离与大图的移动距离成正比
// 遮挡层的移动距离 / 大图的移动距离 = 遮挡层的最大移动距离 / 大图的最大移动距离


// 大图的横向的最大移动距离
var maxX = bigImg.offsetWidth - big.offsetWidth;

// 大图的移动距离 = 遮挡层的移动距离 * 大图的最大移动距离 / 遮挡层的最大移动距离
// 大图的横向移动的坐标
var bigImgMoveX = x * maxX / (small.offsetWidth - mask.offsetWidth);
// 大图的纵向移动的坐标
var bigImgMoveY = y * maxX / (small.offsetWidth - mask.offsetWidth);

// 设置图片移动
bigImg.style.marginLeft = -bigImgMoveX + "px";
bigImg.style.marginTop = -bigImgMoveY + "px";
};