JavaScript实现简易放大镜最全代码解析(ES5)
程序员文章站
2022-04-03 21:08:22
本文实例为大家分享了javascript实现简易放大镜的具体代码,供大家参考,具体内容如下完整代码: &...
本文实例为大家分享了javascript实现简易放大镜的具体代码,供大家参考,具体内容如下
完整代码:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>es5放大镜</title> <style> .box { width: 170px; height: 180px; margin: 100px 200px; border: 1px solid #ccc; position: relative; } .small { position: relative; } .big { width: 300px; height: 320px; position: absolute; top: 30px; left: 220px; overflow: hidden; border: 1px solid #ccc; display: none; } .mask { width: 100px; height: 100px; background: rgba(255,255,0,0.3); position: absolute; top: 0; left: 0; cursor: move; display: none; } .big img{ position: absolute; left: 0; top: 0; } </style> </head> <body> <div class="box" id="box"> <div class="small"> <img src="img/shirt_1.jpg" alt="picture"/> <div class="mask"></div> </div> <div class="big"> <img src="img/shirt_1_big.jpg" alt="picture"/> </div> </div> </body> <script> var box = document.getelementbyid('box'); var small = box.children[0];//放小图的盒子 var big = box.children[1];//放大图的盒子 var mask = small.children[1];//半透明鼠标移动跟随盒子 var bigimage = big.children[0];//大图片 small.onmouseover = function(event){ big.style.display = 'block'; mask.style.display = 'block'; } small.onmouseout = function(){ big.style.display = 'none'; mask.style.display = 'none'; } //移动事件,注意mask的定位相对的是samll small.onmousemove = function(event){ var event = event || window.event;//事件对象 // console.log(this.offsetleft);//0,注意offsetleft返回距离是一个带有定位的父级的左侧距离 var x = event.clientx-this.offsetparent.offsetleft-mask.offsetwidth/2;//此处不能用small的offsetleft,用obj的offsetleft var y = event.clienty-this.offsetparent.offsettop-mask.offsetheight/2; //限制半透明盒子出界 if(x < 0){ x = 0; }else if(x > small.offsetwidth - mask.offsetwidth){ x = small.offsetwidth - mask.offsetwidth; } if( y < 0){ y = 0; }else if( y > small.offsetheight - mask.offsetheight){ y = small.offsetheight - mask.offsetheight; } mask.style.left = x + "px"; mask.style.top = y +"px"; //大图片放大 bigimage.style.left = -x*big.offsetwidth/small.offsetwidth + 'px'; bigimage.style.top = -y*big.offsetheight/small.offsetheight + 'px'; //big.offsetwidth/small.offsetwidth是放大倍数 //因为小图鼠标下移,大图上移,故用负数 } </script> </html>
图片:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 不仅仅会霸榜DXO 华为P40 Pro还有以下亮点
下一篇: 同款有没有