原生js放大镜效果
1、 鼠标放上去会有半透明遮罩、右边会有大图片局部图
2、 鼠标移动时右边的大图片也会局部移动
放大镜的关键原理:
鼠标在小图片上移动时,通过捕捉鼠标在小图片上的位置,定位大图片的相应位置;
放大镜的移动方向和大图片的移动方向:横向和纵向都是相反,才可以保证同步;
页面元素:
技术点:事件捕获,定位
难点:计算
需要元素:小图片和大图片,存放小图片和大图片的容器,有一个放大镜;
涉及到的技术点:
(1) 鼠标事件的捕获:onmouseover(进入)、onmouseout(移除)、onmousemove(移动)
(2) offsetLeft、offsetTop、offsetWidth、offsetHeight、event.clientX、event.clientY
offsetLeft子元素相对于父元素的左位移
offsetWidth,offsetHeight一个元素的宽度和高度,宽度和高度是不包括滚动条的。
event.clientX、event.clientY鼠标的X轴和Y轴,相对于整个页面的坐标,而不是子元素
offsetLeft和style.left对比:
(1)、style.left返回的是字符串,如30px、offsetLeft返回的是数值30;
(2)、style.left是可读写的,offsetLeft是只读的,所以要改变div的位置,只能修改style.left;
(3)、style.left的值需要事先定义,,否则取到的值为空。
style.left只针对在HTML中写的值有效,样式表中无法定义style.left;
制作放大镜所需要的计算
》重点:如何让小图片上的放大镜和大图片同步移动
关键:小图片的比例和大图片的比例是一样的,放大镜比例和右侧大的容器比例是一样的;他们之间的比例是相同的
移动时的比例计算:
放大镜核心计算公式:
编码步骤:
1. 新建html文件;(小图片和大图片的容器盛放)
<div> <div> <div></div> <div></div> <img src="http://www.mamicode.com/imgs/macbook-small.jpg"/> </div> <div> <img src="http://www.mamicode.com/imgs/macbook-big.jpg"/> </div> </div>
2. 设置样式(放大镜漂浮在小容器里面,并且具有一定的透明度,大图片隐藏)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
<style> * { 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 {/*应该是把图片放在这个上面,它的透明度为0,是个block*/ position: absolute; display: block; width: 400px; height: 255px; 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>
3. js逻辑代码
(1) 先捕获元素
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/40037.html