原生js实现放大镜特效
程序员文章站
2023-11-26 14:08:10
本文实例为大家分享了js实现放大镜特效的具体代码,供大家参考,具体内容如下
掌握页面元素定位和移动
放大镜关键原理:鼠标在小图片上移动时,通过捕捉鼠标在小图片上的位置定...
本文实例为大家分享了js实现放大镜特效的具体代码,供大家参考,具体内容如下
掌握页面元素定位和移动
放大镜关键原理:鼠标在小图片上移动时,通过捕捉鼠标在小图片上的位置定位大图片的相应位置
技术点:事件捕获、定位
offsetleft与style.left的对比:
1)offsetleft是与父级元素的距离,不包过滚动条的距离
2)style.left返回的是字符串,如30px,offsetleft返回的是数值30
3)style.lft是可读写的,offsetleft是只读的,所以要改变div的位置只能修改style.left
4)style.left的值需要事先定义,否则取到的值为空
难点:计算:如何让小图片的放大镜和大图片同步移动
距离定位图解:
具体代码:
<!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 id="demo"> <div id="small-box"> <div id="mark"></div> <div id="float-box"></div> <img src="img/macbook-small.jpg" /> </div> <div id="big-box"> <img src="img/macbook-big.jpg" /> </div> </div> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。