javascript 实现图片放大镜功能
淘宝上经常用到的一个功能是利用图片的放大镜功能来查看商品的细节
下面我们来实现这样一个功能吧,原理很简单:
实现一个可以随鼠标移动的虚框
在另外一个块中对应显示虚框中的内容
实现思路:
虚框用css中的透明度实现filter:alpha(opacity:20); opacity:0.2;
鼠标移动到小图上面时:虚框出现,大图对应出现
细节注意的地方:
1:虚框的定位:保持鼠标位于虚框的中心,如何处理鼠标中心距离四边距离小于虚框半径(或者方形的边长的一半)的情况?
2:保持大图中显示的内容是虚框选中的内容(保持大小图的比例问题)
代码如下:
<!DOCTYPE html> <html> <head> <title>js_study</title> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <script src="js_study.js" type="text/javascript" charset="utf-8"></script> <style> #div1 { width:280px; height:200px; position:relative; margin:30px auto 0px;} #div1 img{width:280px; height:200px;} #div1 span { width:100px; height:100px; background:blue; left:0px;top:0px; position:absolute; display:none; filter:alpha(opacity:20); opacity:0.2;} .show { width:100%; height:100%; background:blue; position:absolute; z-index:10px; filter:alpha(opacity:10); opacity:0.1; left:0px; top:0px; } #div2 {width:400px; height:400px; position:relative; display:none; overflow:hidden; margin:0px auto 0px;} #img1 { position:absolute;} </style> </head> <body style="margin 0px; text-align: center" onload="init();" > <div id="div1"> <img src="./num/2.jpg"> <span style="display: none; left: 204px; top: 41px;"></span> <div class="show"></div> </div> <div id="div2" style="display: none;"> <img id="img1" src="./num/2.jpg" style="left: -610px; top: -149.21311475409834px;"> </div> </body> </html>
//放大镜效果 var moveme = false; function init () { var d1 = document.getElementById('div1'); var the_float = d1.getElementsByTagName('div')[0]; var the_span = d1.getElementsByTagName('span')[0]; var the_img = document.getElementById('img1'); the_float.onmouseover = function () { the_span.style.display = 'block'; the_img.parentNode.style.display = 'block'; } the_float.onmouseout = function () { the_span.style.display = 'none'; the_img.parentNode.style.display = 'none'; } the_float.onmousemove = function (ev) { var oEvent = ev||window.event; var x = oEvent.clientX - d1.offsetLeft - the_span.offsetWidth/2;//鼠标横坐标-父块距离浏览器窗口左距离-虚框的半 var y = oEvent.clientY - d1.offsetTop - the_span.offsetHeight/2; //小图区域 if(x<0) x=0;//左边界 else if(x>the_float.offsetWidth - the_span.offsetWidth)//右边界 x = the_float.offsetWidth - the_span.offsetWidth; if(y<0) y= 0;//上边界 else if(y>the_float.offsetHeight - the_span.offsetHeight)//下边界 y = the_float.offsetHeight -the_span.offsetHeight; the_span.style.left = x+"px"; the_span.style.top = y+"px"; //大图对应区域 var percentX = x/(the_float.offsetWidth - the_span.offsetWidth);//计算比例 var percentY = y/(the_float.offsetHeight - the_span.offsetHeight); var iParent = the_img.parentNode; //保持大小图之间的比例关系 the_img.style.width = parseFloat(the_float.offsetWidth)/parseFloat(the_span.offsetWidth)*parseFloat(iParent.offsetWidth)+"px"; the_img.style.left = -percentX*(the_img.offsetWidth - iParent.offsetWidth)+"px"; the_img.style.top = -percentY*(the_img.offsetHeight - iParent.offsetHeight)+"px"; } }