放大镜
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { padding: 0px; margin: 0px; } .min { width: 450px; height: 450px; border: 1px solid red; position: relative; margin: 20px; } .min img { width: 100%; height: 100%; } .mask { width: 150px; height: 150px; background-color: rgba(170, 182, 11, 0.5); position: absolute; left: 0px; top: 0px; display: none; } .max { width: 500px; height: 500px; border: 1px solid red; overflow: hidden; position: absolute; left: 550px; top: 110px; display: none; } .maxImg { position: absolute; } </style> </head> <body> <div class="min"> <img src="images/min.jpg" alt=""> <div class="mask"></div> </div> <div class="max"> <img src="images/max.jpg" alt="" class="maxImg"> </div> <script> var min = document.querySelector('.min'); console.log(min); var mask = document.querySelector('.mask'); console.log(mask); var max = document.querySelector('.max'); console.log(max); var maxImg = document.querySelector('.maxImg'); console.log(maxImg); min.onmouseover = function() { mask.style.display = 'block'; max.style.display = 'block'; } min.onmouseleave = function() { mask.style.display = 'none'; max.style.display = 'none'; } min.onmousemove = function(e) { // 蒙版在小盒子中的位置 var maskX = e.pageX - min.offsetLeft; var maskY = e.pageY - min.offsetTop; // 光标在蒙版的中间 maskX = maskX - mask.offsetWidth / 2; maskY = maskY - mask.offsetHeight / 2; // 蒙版可以在小盒子上移动的最大距离 var maskMoveX = min.offsetWidth - mask.offsetWidth; var maskMoveY = min.offsetHeight - mask.offsetHeight; //如果移动的距离大于最大距离,则就让最大移动距离等于移动的距离 if (maskX > maskMoveX) { maskX = maskMoveX; } else if (maskX <= 0) { maskX = 0; } if (maskY > maskMoveY) { maskY = maskMoveY; } else if (maskY <= 0) { maskY = 0; } // 设置蒙版的位置 mask.style.left = maskX + 'px'; mask.style.top = maskY + 'px'; // 设置比例关系 var rotateX = maskX / maskMoveX; var rotateY = maskY / maskMoveY; maxImg.style.left = -rotateX * (maxImg.offsetWidth - max.offsetWidth) + 'px'; maxImg.style.top = -rotateY * (maxImg.offsetHeight - max.offsetHeight) + 'px'; } </script> </body> </html>