放大镜效果
需求:
1.鼠标移至图片上方,鼠标周围出现黄色的的正方形框,黄色矩形框会随着鼠标的移动而移动;
2.将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。
实现原理:
获得鼠标在盒子的坐标,设置鼠标移入移出事件,移入时用设置放大镜显示,移出则隐藏,遮挡层的最大移动距离为小图片盒子宽度减去遮挡层宽度
damo10
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.box {width: 400px;height: 400px;}.content {width: 400px;height: 400px;position: relative;border: 1px solid #ccc;}.content>img {width: 400px;height: 400px;}.mask {width: 100px;height: 100px;background-color:#ccc;opacity: 0.5;position: absolute;top: 0;left: 0;border: 1px solid #ccc;display: none;}.big {width: 400px;height: 400px;position: absolute;top: 0;left: 410px;border: 1px solid #ccc;overflow: hidden;display: none;}.big>img {width: 800px;height: 800px;position: absolute;top: 0;left: 0;}</style>
</head><body><div class="box"><div class="content"><img src="./素材库/1.jpg" alt=""><div class="mask"></div><div class="big"><img src="./素材库/1.jpg" alt=""></div></div></div><script>var content = document.querySelector('.content')var mask = document.querySelector('.mask')var big = document.querySelector('.big')content.addEventListener('mouseenter', function () {mask.style.display = 'block'big.style.display = 'block'})content.addEventListener('mouseleave', function () {console.log(1111);mask.style.display = 'none'big.style.display = 'none'})content.addEventListener('mousemove', function (e) {var x = e.pageX - content.offsetLeftvar y = e.pageY - content.offsetTopvar maskX = x - mask.offsetWidth / 2var maskY = y - mask.offsetHeight / 2console.log(mask.offsetWidth, content.offsetWidth);var XMAX = content.offsetWidth - mask.offsetWidthvar YMAX = content.offsetHeight - mask.offsetHeightconsole.log(maskX, maskY, XMAX);if (maskX <= 0) {maskX = 0} else if (maskX >= XMAX) {maskX = XMAX}if (maskY <= 0) {maskY = 0} else if (maskY >= YMAX) {maskY = YMAX}mask.style.left = maskX + 'px'mask.style.top = maskY + 'px'var img = document.querySelector('.big>img')imgXMax = img.offsetWidth - big.offsetWidthimgYMax = img.offsetHeight - big.offsetHeightimg.style.left = -maskX * imgXMax / XMAX + 'px'img.style.top = -maskY * imgYMax / YMAX + 'px'})</script>
</body>
</html>