Js实现放大镜案例

it2025-03-07  28

Js实现放大镜案例

当鼠标放在图片上时,会在图片上出现遮罩层,同时在图片右面显示遮罩层覆盖处放大的图片,具体效果详见各大购物网站的页面

HTML和CSS代码

<!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> * { margin: 0; padding: 0; } .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; } .big img { position: absolute; width: 800px; } .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; } </style> </head> <body> <div class="box" id="box"> <div class="small"> <img src="images/small.jpg" width="350" alt="" /> <div class="mask"></div> </div> <div class="big"> <img src="images/big.jpg" alt="" /> </div> </div> </body> </html>

思路

当鼠标移入图片上显示遮罩层和大盒子,移出时隐藏 // 获取元素 var box = document.getElementById('box') var small = box.children[0] var mask = small.children[1] var big = box.children[1] var img = big.children[0] // 为防止冒泡,使用onmouseenter和onmouseleave事件 small.onmouseenter = function () { mask.style.display = 'block' big.style.display = 'block' } small.onmouseleave = function () { mask.style.display = 'none' big.style.display = 'none' } 让遮罩层跟随鼠标在小盒子中移动 small.onmousemove = function (e) { e = e || window.event // 解决兼容性问题 // 要让鼠标在遮罩层中间显示 x = e.pageX - box.offsetLeft - mask.clientWidth / 2 y = e.pageY - box.offsetTop - mask.clientHeight / 2 // 判断mask是否超出盒子,若超出则固定盒子位置 x = x < 0 ? 0 : x y = y < 0 ? 0 : y x = x > box.offsetWidth - mask.offsetWidth ? box.offsetWidth - mask.offsetWidth : x y = y > box.offsetHeight - mask.offsetHeight ? box.offsetHeight - mask.offsetHeight : y // 将位置赋值给遮罩层 mask.style.left = x + 'px' mask.style.top = y + 'px' } 右侧大盒子中的图片跟随遮罩层的位置移动,实现放大的效果。完整代码如下 small.onmousemove = function (e) { e = e || window.event // 解决兼容性问题 x = e.pageX - box.offsetLeft - mask.clientWidth / 2 y = e.pageY - box.offsetTop - mask.clientHeight / 2 // 判断mask是否超出盒子,若超出则固定盒子位置 x = x < 0 ? 0 : x y = y < 0 ? 0 : y x = x > box.offsetWidth - mask.offsetWidth ? box.offsetWidth - mask.offsetWidth : x y = y > box.offsetHeight - mask.offsetHeight ? box.offsetHeight - mask.offsetHeight : y mask.style.left = x + 'px' mask.style.top = y + 'px' // 大盒子图片等比例移动 // 小盒子移动距离 / 小盒子最大移动距离 == 大盒子移动距离 / 大盒子最大移动距离 var bigX = x / (box.offsetWidth - mask.offsetWidth) * (img.offsetWidth - big.offsetWidth) var bigY = y / (box.offsetHeight - mask.offsetHeight) * (img.offsetHeight - big.offsetHeight) img.style.left = -bigX + 'px' img.style.top = -bigY + 'px' }

这个案例主要是要熟练运用offset、client等获取距离和宽高的属性,整体思想就是用鼠标的位置赋值到遮罩层,来实现跟随鼠标移动的效果,和大盒子的图片跟随遮罩层等比例移动,同时要注意为防止冒泡用onmouseenter和onmouseleave替换onmouseover和onmouseout事件

最新回复(0)