1 <script> 2 3 // 当页面加载完成后执行 4 window.addEventListener('load', function () { 5 6 //查找元素 7 //small 小图div 8 var small = document.querySelector('.small') 9 //小图遮罩层div 10 var mask = document.querySelector('.mask') 11 //大图div 12 var big = document.querySelector('.big') 13 14 //当鼠标经过 主图时 时执行-显示大图 15 small.addEventListener('mouseover', function () { 16 mask.style.display = 'block' 17 big.style.display = 'block' 18 }) 19 20 //当鼠标离开 主图时 时执行-隐藏大图 21 small.addEventListener('mouseout', function () { 22 mask.style.display = 'none' 23 big.style.display = 'none' 24 }) 25 26 //当鼠标在主图内 移动时 执行 27 small.addEventListener('mousemove', function (e) { 28 //获取鼠标在主图盒子内的XY坐标,减去偏移值 29 var x = e.pageX - this.offsetLeft 30 var y = e.pageY - this.offsetTop 31 32 //将获取到的鼠标XY坐标,赋值给 mask遮罩层盒子的定位坐标 33 //注意一定后面+'px',不然没效果 34 var maskX = x - mask.offsetWidth / 2 35 var maskY = y - mask.offsetTop / 2 36 37 //遮罩最大移动距离 38 var maskMax = small.offsetWidth - mask.offsetWidth 39 40 //限制X轴移动范围 41 if (maskX <= 0) { 42 maskX = 0 43 } else if (maskX >= maskMax) { 44 maskX = small.offsetWidth - mask.offsetWidth 45 } 46 47 //限制Y轴移动范围 48 if (maskY <= 0) { 49 maskY = 0 50 } else if (maskY >= maskMax) { 51 maskY = maskMax 52 } 53 54 mask.style.left = maskX + 'px' 55 mask.style.top = maskY + 'px' 56 57 //获取大图 58 var big_img = document.querySelector('.big_img') 59 60 //大图最大移动距离 61 var bigImgMax = big_img.offsetWidth - big.offsetWidth 62 63 //大图的X轴移动距离 64 var bigImgX = maskX * bigImgMax / maskMax 65 66 //大图的Y轴移动距离 67 var bigImgY = maskY * bigImgMax / maskMax 68 69 //坐标赋值,让大图跟着遮罩层一起移动 70 big_img.style.left = -bigImgX + 'px' 71 big_img.style.top = -bigImgY + 'px' 72 }) 73 }) 74 </script>
1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>图片放大镜效果</title> 8 <style> 9 .small { 10 position: relative; 11 546px; 12 height: 546px; 13 margin: 50px 100px; 14 15 background: rgba(251, 227, 227, 0.979) 16 } 17 18 .small .phone_img { 19 20 100%; 21 height: 100%; 22 } 23 24 .mask { 25 display: none; 26 position: absolute; 27 left: 0; 28 top: 0; 29 200px; 30 height: 200px; 31 border: 1px solid rgb(68, 0, 255); 32 background: rgba(12, 12, 12, 0.1); 33 /* 只要鼠标放到遮罩层上就变成十字形状 */ 34 cursor: move; 35 } 36 37 .big { 38 display: none; 39 position: absolute; 40 right: -820px; 41 top: 0; 42 819px; 43 height: 819px; 44 background: rgb(255, 254, 254); 45 z-index: 99; 46 border: 1px solid #ccc; 47 48 /* 超出的部分隐藏 */ 49 overflow: hidden; 50 } 51 52 .big .big_img { 53 position: absolute; 54 left: 0; 55 top: 0; 56 1092px; 57 height: 1092px; 58 } 59 </style> 60 </head> 61 62 <body> 63 <div class="small"> 64 <img src="../img/huaweip40.jpg" alt="" class="phone_img"> 65 <div class="mask"></div> 66 <div class="big"> 67 <img src="../img/hwp402-big.jpg" alt="" class="big_img"> 68 </div> 69 </div> 70 71 </body> 72 73 </html>
效果图