JavaScript实现简易放大镜最全代码解析(ES5)
更新时间:2021年09月10日 10:33:40 作者:飒尔
这篇文章主要为大家详细介绍了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>
图片:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
谈谈基于iframe、FormData、FileReader三种无刷新上传文件的方法
发请求有两种方式,一种是用ajax,另一种是用form提交,默认的form提交如果不做处理的话,会使页面重定向。本篇文章通过实例给大家介绍基于iframe/FormData/FileReader三种无刷新上传文件的方法,感兴趣的朋友一起学习吧2015-12-12JavaScript基于DOM操作实现简单的数学运算功能示例
这篇文章主要介绍了JavaScript基于DOM操作实现简单的数学运算功能,涉及javascript节点操作、元素遍历及数学运算相关操作技巧,需要的朋友可以参考下2017-01-01JavaScript精炼之构造函数 Constructor及Constructor属性详解
对象的constructor属性用于返回创建该对象的函数,也就是我们常说的构造函数,除了创建对象,构造函数(constructor) 还做了另一件有用的事情—自动为创建的新对象设置了原型对象(prototype object)2015-11-11
最新评论