Posted in Javascript onFebruary 28, 2017
效果图:(实例图片由自己添加)
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>仿淘宝放大镜特效</title> <style type="text/css"> *{margin: 0;padding: 0;} #demo{width:350px;height:350px;border: 1px solid #000;position:relative;margin:100px;} #smil_box{width: 350px;height: 350px;position:relative;} #mask{width:175px;height: 175px;background:rgba(255,255,0,0.4);position:absolute;top:0;left:0;display:none;cursor:move;} #big_box{width: 400px;height: 400px;position:absolute;top:0;left:360px;border: 1px solid #000;overflow:hidden;display:none;} #big_box img{position:absolute;top:0;left:0;} </style> </head> <body> <div id="demo"> <div id="smil_box"> <img src="http://www.qdfuns.com/misc.php?mod=attach&genre=editor&aid=193662baf63738c68b594f3ec920769f" height="350" width="350" alt=""> <div id="mask"></div> </div> <div id="big_box"> <img src="http://www.qdfuns.com/misc.php?mod=attach&genre=editor&aid=3e8b3554eb90dd13fa0f82465ac6d382" height="800" width="800" alt="" id="big_img"> </div> </div> </body> <script type="text/javascript"> (function(window){ function $(id){ return document.getElementById(id); }; // 获取对象 var demo = $("demo"),smilBox = $("smil_box"),mask = $("mask"),bigImg = $("big_img"),bigBox = $("big_box"); // smilBox的hover事件 smilBox.onmouseover = function(){ mask.style.display = "block"; bigBox.style.display = "block"; }; smilBox.onmouseout = function(){ mask.style.display = "none"; bigBox.style.display = "none"; }; // 鼠标移动事件 smilBox.onmousemove = function(event){ var event = event || window.event; // 获取鼠标在页面上的坐标 var pageX = event.pageX || event.clientX + document.documentElement.scrollLeft; var pageY = event.pageY || event.clientY + document.documentElement.scrollTop; // mask的位置坐标 var boxX = pageX - demo.offsetLeft; var boxY = pageY - demo.offsetTop; var maskX = boxX - mask.offsetWidth / 2; var maskY = boxY - mask.offsetHeight / 2; // 限制mask的移动范围 if( maskX < 0 ){ maskX = 0; }; if( maskX > smilBox.offsetWidth - mask.offsetWidth){ maskX = smilBox.offsetWidth - mask.offsetWidth; }; if( maskY < 0 ){ maskY = 0; }; if( maskY > smilBox.offsetHeight - mask.offsetHeight){ maskY = smilBox.offsetHeight - mask.offsetHeight; }; // 黄色遮罩层的位置坐标 mask.style.top = maskY + "px"; mask.style.left = maskX + "px"; // 大图片移动的比例 var prop = ( bigImg.offsetWidth - bigBox.offsetWidth ) / (smilBox.offsetWidth - mask.offsetWidth); // 大图片的坐标 var bigImgX = prop * maskX; var bigImgY = prop * maskY; bigImg.style.top = -bigImgY + "px"; bigImg.style.left = -bigImgX + "px"; } })(window) </script> </html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!
原生js仿淘宝网商品放大镜效果
- Author -
chang红达声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@