原生js实现放大镜特效

掌握页面元素定位和移动

放大镜关键原理:鼠标在小图片上移动时,通过捕捉鼠标在小图片上的位置定位大图片的相应位置

技术点:事件捕获、定位

offsetLeft与style.left的对比:
1)offsetLeft是与父级元素的距离,不包过滚动条的距离
2)style.left返回的是字符串,如30px,offsetLeft返回的是数值30
3)style.lft是可读写的,offsetLeft是只读的,所以要改变div的位置只能修改style.left
4)style.left的值需要事先定义,否则取到的值为空
难点:计算:如何让小图片的放大镜和大图片同步移动

距离定位图解:

原生js实现放大镜特效

具体代码:

<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <style type="text/css"> *{ margin: 0; padding: 0; } #demo{ display: block; width: 400px; height: 255px; margin: 50px; position: relative; border: 1px solid #ccc; } #small-box{ position: relative; z-index: 1; } #float-box{ display: none; width: 160px; height: 120px; position: absolute; background: #ffffcc; border: 1px solid #ccc; filter: alpha(opacity=50); opacity: 0.5; } #mark{ position: absolute; display: block; width: 400px; height: 255px; background-color: #fff; filter: alpha(opacity=0); opacity: 0; z-index: 10; } #big-box{ display: none; position: absolute; top: 0; left: 460px; width: 400px; height: 300px; overflow: hidden; border: 1px solid #ccc; z-index: 1; } #big-box img{ position: absolute; z-index: 5; } </style> <script> window.onload=function(){ var $=function(id){ return document.getElementById(id); } var Demo = $("demo"); var SmallBox = $("small-box"); var Mark = $("mark"); var FloatBox = $("float-box"); var BigBox = $("big-box"); var BigBoxImage = BigBox.getElementsByTagName("img")[0]; Mark.onmouseover = function(){ FloatBox.style.display = "block"; BigBox.style.display = "block"; } Mark.onmouseout = function(){ FloatBox.style.display = "none"; BigBox.style.display = "none"; } Mark.onmousemove = function(e){ var _event = e||window.event//兼容多个浏览器的参数模式 var left = _event.clientX - Demo.offsetLeft - SmallBox.offsetLeft - FloatBox.offsetWidth/2; var top = _event.clientY - Demo.offsetTop - SmallBox.offsetTop - FloatBox.offsetHeight/2; if(left < 0){ left = 0; }else if(left > Mark.offsetWidth - FloatBox.offsetWidth){ left = Mark.offsetWidth - FloatBox.offsetWidth; } if(top < 0){ top = 0; }else if(top > Mark.offsetHeight - FloatBox.offsetHeight){ top = Mark.offsetHeight - FloatBox.offsetHeight; } FloatBox.style.left = left + 'px'; FloatBox.style.top = top + 'px'; var percentX = left / (Mark.offsetWidth - FloatBox.offsetWidth); var percentY = top / (Mark.offsetHeight - FloatBox.offsetHeight); BigBoxImage.style.left = -percentX * (BigBoxImage.offsetWidth - BigBox.offsetWidth)+'px'; BigBoxImage.style.top = -percentY * (BigBoxImage.offsetHeight - BigBox.offsetHeight)+'px'; } } </script> <body> <div> <div> <div></div> <div></div> <img src="https://www.jb51.net/img/macbook-small.jpg" /> </div> <div> <img src="https://www.jb51.net/img/macbook-big.jpg" /> </div> </div> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwwsgj.html