我们在网上经常会碰到图片预览鼠标经过局部放大图片的效果,今天我们就来看看这个效果是如何实现的。
实现方法
借助宽高等比例放大的两张图片,结合JavaScript中鼠标偏移量、元素偏移量、元素自身宽高等属性完成;
左侧遮罩移动Xpx,右侧大图移动X*倍数px;看起来是不是很简单呢,下面我们就来看看具体如何实现。
举例
<!DOCTYPE html> <html> <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>JavaScript实现图片预览放大镜效果(含源码)www.woaidaogu.com</title> <meta charset="utf-8" /> <style type="text/css"> * { margin: 0px; padding: 0px; } .wrap { height: 480px; margin: 30px; } #small { width: 600px; height: 400px; position: relative; } #small img { width: 100%; height: 100%; } .wrap div { float: left; margin-right: 10px; } #big { width: 600px; height: 400px; overflow: hidden; position: relative; display: none; } #hua { position: absolute; left: 0px; top: 0px; } #move { width: 100px; height: 100px; background: #000; opacity: 0.5; position: absolute; display: none; left: 0px; top: 0px; } </style> </head> <body> <div> <div id="small"> <img src="images/hua.jpg" /> <p id="move"></p> </div> <div id="big"> <img src="images/hua.jpg" id="hua" /> </div> </div> <script type="text/javascript"> var move = document.getElementById('move'); var small = document.getElementById('small'); var big = document.getElementById('big'); var hua = document.getElementById('hua'); small.onmousemove = function (event) { event = event || window.event; this.style.cursor = 'move'; // 计算move移动块的left值 var move_left = event.clientX - this.offsetLeft - move.offsetWidth / 2; // 计算move移动块的top值 var move_top = event.clientY - this.offsetTop - move.offsetHeight / 2; // 超出左边界赋值为0 move_left = move_left < 0 ? 0 : move_left; // 超出右边界赋值为盒子宽度-移动块的宽度 move_left = move_left > this.offsetWidth - move.offsetWidth ? this.offsetWidth - move.offsetWidth : move_left; // 超出上边界赋值为0 move_top = move_top < 0 ? 0 : move_top; // 超出下边界赋值为盒子高度-移动块高度 move_top = move_top > this.offsetHeight - move.offsetHeight ? this.offsetHeight - move.offsetHeight : move_top; // 修改移动块left、top值 move.style.left = move_left + 'px'; move.style.top = move_top + 'px'; /* 计算图片需要移动的坐标 距离左边left 图片宽度 盒子宽度 距离左边left 图片宽度 盒子宽度 big_x/(hua.offsetWidth-big.offsetWidth) = move_left/(small.offsetWidth-move.offsetWidth); big_y/(hua.offsetHeight-big.offsetHeight) = move_top/(small.offsetHeight-move.offsetHeight); */ var big_x = (move_left / (small.offsetWidth - move.offsetWidth)) * (hua.offsetWidth - big.offsetWidth); var big_y = (move_top / (small.offsetHeight - move.offsetHeight)) * (hua.offsetHeight - big.offsetHeight); // 修改图片定位 hua.style.left = -big_x + 'px'; hua.style.top = -big_y + 'px'; }; small.onmouseover = function () { move.style.display = 'block'; big.style.display = 'block'; }; small.onmouseout = function () { move.style.display = 'none'; big.style.display = 'none'; }; </script> </body> </html>
通过以上内容我们知道了JavaScript如何实现图片预览放大镜效果,感谢您访问“我爱捣鼓(www.woaidaogu.com)”网站的内容,希望对大家有所帮助!引用本文内容时,请注明出处!谢谢合作!