JavaScript仿京东放大镜特效
本文实例为大家分享了JavaScript仿京东放大镜的具体代码,供大家参考,具体内容如下
功能需求:
1、分为三个模块
2、鼠标经过小图片盒子,黄色的遮挡层和大图片盒子显示,离开隐藏两个盒子功能
3、黄色的遮挡层跟随着鼠标移动
4、移动黄色遮挡层,大图片跟随着移动
大图片移动距离=(遮挡层移动距离*大图片最大移动距离)/ 遮挡层最大移动距离
<style> body, div { margin: 0; padding: 0; } .product { position: relative; width: 400px; height: 400px; margin: 50px 0 0 20px; border: 1px solid #000; } .preview_img img { width: 300px; height: 300px; margin: 50px 50px; } .mask { position: absolute; display: none; top: 20px; left: 30px; width: 80px; height: 80px; background-color: yellow; opacity: 0.5; cursor: move; } .big { position: absolute; display: none; left: 410px; top: 0; width: 500px; height: 500px; z-index: 999; overflow: hidden; } .big img { position: absolute; top: 0; left: 0; width: 400px; height: 400px; } </style> <!-- 引入js文件 --> <script src="detail.js"></script> </head> <body> <div class="product"> <div class="preview_img"> <img src="images/xs.jpg" alt="" /> <div class="mask"></div> <div class="big"> <img src="images/xs.jpg" alt="" class="bigImg" /> </div> </div> </div> </body>
JS页面
//页面预加载 window.addEventListener("load", function () { var preview_img = document.querySelector(".preview_img"); var mask = document.querySelector(".mask"); var big = document.querySelector(".big"); //1.鼠标经过 preview_img 就显示和隐藏 mask 遮挡层 和 big 大盒子 preview_img.addEventListener("mouseover", function () { mask.style.display = "block"; big.style.display = "block"; }); preview_img.addEventListener("mouseout", function () { mask.style.display = "none"; big.style.display = "none"; }); //把鼠标坐标给遮挡层是不合适的,因为遮挡层坐标以父盒子为准 preview_img.addEventListener("mousemove", function (e) { //(1)先计算出鼠标在盒子内的坐标 var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; //(2)减去盒子高度宽度的一半 //(3)mask 移动的距离 var maskX = x - mask.offsetWidth / 2; var maskY = y - mask.offsetHeight / 2; //(4)如果坐标小于0 就让他停在 0 的位置(即超出盒子范围就停止) var egdeX = preview_img.offsetWidth - mask.offsetWidth; var egdeY = preview_img.offsetHeight - mask.offsetHeight; if (maskX <= 0) { maskX = 0; } else if (maskX >= egdeX) { maskX = egdeX; } if (maskY <= 0) { maskY = 0; } else if (maskY >= egdeY) { maskY = egdeY; } mask.style.left = maskX + "px"; mask.style.top = maskY + "px"; //大图片的移动距离 = 遮挡层移动距离*大图片最大移动距离 / 遮挡层的最大移动距离 var bigImg = document.querySelector(".bigImg"); //大图片最大移动距离 var bigMax = bigImg.offsetWidth - big.offsetWidth; //大图片的移动距离 x y var bigX = (maskX * bigMax) / egdeX; var bigY = (maskY * bigMax) / egdeY香港高防服务器http://www.558idc.com/hkgf.html; bigImg.style.left = -bigX + "px"; bigImg.style.top = -bigY + "px"; }); });
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持hwidc。