图片放大镜js特效
今天看js教程,做了一个js放大镜效果,小小的开心了一把.下面为js源码:
View Code
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>放大镜效果</title> <style type="text/css"> #div1 { width: 200px; height: 150px; padding: 5px; border: 1px solid #ccc; position: relative; } #div1 .small_Pic { width: 200px; height: 150px; background: #eee; position: relative; } #div1 .float_layer { width: 50px; height: 50px; border: 1px solid #000; background: #fff; filter: alpha(opacity=30); opacity: 0.3; position: absolute; top: 0; left: 0; display: none; } #div1 .mark { width: 100%; height: 100%; position: absolute; z-index: 2; left: 0px; top: 0px; background: red; filter: alpha(opacity=0); opacity: 0; } #div1 .big_Pic { position: absolute; top: -1px; left: 315px; width: 200px; height: 235px; overflow: hidden; border: 2px solid #ccc; display: none; } #div1 .big_Pic img { position: absolute; top: 0px; left: 0px; } </style> <script type="text/javascript"> window.onload = function () { var oDiv = document.getElementById("div1"); var oMark = getByClass(oDiv, 'mark')[0]; var oFloat = getByClass(oDiv, 'float_layer')[0]; var oBig = getByClass(oDiv, 'big_Pic')[0]; var oSmall = getByClass(oDiv, 'small_Pic')[0]; var oImg = oBig.getElementsByTagName('img')[0]; oMark.onmouseover = function () { oFloat.style.display = 'block'; oBig.style.display = 'block'; } oMark.onmouseout = function () { oFloat.style.display = 'none'; oBig.style.display = 'none'; } oMark.onmousemove = function (ev) { var oEvent = ev || event; var l = oEvent.clientX - oSmall.offsetLeft - oDiv.offsetLeft - oFloat.offsetWidth / 2; var t = oEvent.clientY - oSmall.offsetTop - oDiv.offsetTop - oFloat.offsetHeight / 2; if (l < 0) { l = 0; } else if (l > oMark.offsetWidth - oFloat.offsetWidth) { l = oMark.offsetWidth - oFloat.offsetWidth; } if (t < 0) { t = 0; } else if (t > oMark.offsetHeight - oFloat.offsetHeight) { t = oMark.offsetHeight - oFloat.offsetHeight; } oFloat.style.left = l + "px"; oFloat.style.top = t + "px"; var percentX = l / (oMark.offsetWidth - oFloat.offsetWidth) * (oImg.offsetWidth - oBig.offsetWidth); var percentY = t / (oMark.offsetHeight - oFloat.offsetHeight) * (oImg.offsetHeight - oBig.offsetHeight); oImg.style.left = -percentX + "px"; oImg.style.top = -percentY + "px"; } } //根据class获取元素 function getByClass(oParent, sClass) { var aEle = oParent.getElementsByTagName('*'); var aTemp = []; for (var i = 0; i < aEle.length; i++) { if (aEle[i].className == sClass) { aTemp.push(aEle[i]); } } return aTemp; } </script> </head> <body> <div id="div1"> <div class="small_Pic"> <span class="mark"></span> <span class="float_layer"></span> <img src="http://pic002.cnblogs.com/images/2012/297868/2012060918344911.jpg" alt="小图" /> </div> <div class="big_Pic"> <img src="http://pic002.cnblogs.com/images/2012/297868/2012060918343324.jpg" alt="大图" /> </div> </div> </body> </html>