css代码
1 body{
2 margin: 0;
3 }
4 .box {
5 width: 1210px;
6 position: relative;
7 background-color: pink;
8 margin: 0 auto;
9 }
10
11 .content {
12 width: 452px;
13 height: 568px;
14 border: 1px solid #eee;
15 }
16
17 .mask {
18 display: none;
19 width: 200px;
20 height: 200px;
21 position: absolute;
22 top: 0;
23 left: 0;
24 background-color: #FEDE4F;
25 opacity: 0.5;
26 cursor: move;
27 }
28
29 .big {
30 display: none;
31 position: absolute;
32 left: 453px;
33 top: 0;
34 width: 500px;
35 height: 570px;
36 background-color: rgb(192, 173, 173);
37 z-index: 999;
38 border: 1px solid #eee;
39 overflow: hidden;
40 }
41 .big img{
42 position: absolute;
43 top: 0;
44 left: 0;
45 }
1 <div class="box">
2 <div class="content">
3 <img src="../imges/p40.jpg" alt="">
4 <div class="mask"></div>
5 <div class="big"><img src="../imges/p40pro.jpg" alt="" id="bigImg"></div>
6 </div>
7 </div>
JS代码
1 window.addEventListener('load', function () {
2 var content = document.querySelector('.content')
3 var mask = document.querySelector('.mask')
4 var big = document.querySelector('.big')
5 var box = document.querySelector('.box')
6 // 当鼠标进入盒子里面就显示mask和big
7 content.addEventListener('mouseover', function () {
8 mask.style.display = 'block'
9 big.style.display = 'block'
10 })
11 content.addEventListener('mouseout', function () {
12 mask.style.display = 'none'
13 big.style.display = 'none'
14 })
15 // 鼠标移动的时候黄色背景层跟着移动
16 content.addEventListener('mousemove', function (e) {
17 var x = e.pageX - box.offsetLeft;
18 var y = e.pageY - box.offsetTop;
19 // mask移动的距离
20 var maskX = x - mask.offsetWidth / 2;
21 var maskY = y - mask.offsetWidth / 2;
22
23 // 黄色背景图层最大移动距离
24 var maskMax = content.offsetWidth - mask.offsetWidth;
25 if (maskX <= 0) {
26 maskX = 0
27 } else if (maskX >= maskMax) {
28 maskX = maskMax;
29 }
30 if (maskY <= 0) {
31 maskY = 0;
32 } else if (maskY >= maskMax) {
33 maskY = maskMax;
34 }
35 mask.style.left = maskX + 'px'
36 mask.style.top = maskY + 'px'
37 // 大图片的移动距离 = 黄色背景图层移动距离 * 大图片最大移动距离 / 黄色背景图层最大移动距离
38 var bigImg = document.querySelector('#bigImg')
39 var bigMax = bigImg.offsetWidth - big.offsetWidth;
40 // 大图片的移动距离
41 var bigX = maskX * bigMax / maskMax;
42 var bigY = maskY * bigMax / maskMax;
43 bigImg.style.left = -bigX + 'px';
44 bigImg.style.top = -bigY + 'px';
45 })
46 })
效果图