JS 放大鏡特效
阿新 • • 發佈:2019-02-15
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>放大鏡效果</title> <style type="text/css"> #div1{ width: 200px; height: 200px; padding: 5px; border: 1px solid #ccc; position: relative; } #div1 .small_pic{ width: 200px; height: 200px; background: #eee; position: relative; } #div1 .float_layer{ width: 50px; height: 50px; border:1px solid #000; background: #fff; opacity: 0.3; position: absolute; top: 0px; left: 0px; display: none; } #div1 .mark{ width: 100%; height:100%; position: absolute; z-index: 2; left: 0px; top: 0px; background: red; opacity: 0; } #div1 .big_pic{ position: absolute; top: -1px; left: 215px; width: 450px; height: 450px; overflow: hidden; border: 2px solid #ccc; display: none; } #div1 .big_pic img{ position: absolute; top: 0px; left: 0px; } </style> <script type="text/javascript"> function getByClass(oParent, sClass) { var aEle=oParent.getElementsByTagName('*'); var aTmp=[]; var i=0; for(i=0;i<aEle.length;i++) { if(aEle[i].className==sClass) { aTmp.push(aEle[i]); } } return aTmp; } 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-oDiv.offsetLeft-oSmall.offsetLeft-oFloat.offsetWidth/2; var t=oEvent.clientY-oDiv.offsetTop-oSmall.offsetTop-oFloat.offsetHeight/2; if(l<-5) { l=-5; } else if (l>oMark.offsetWidth-oFloat.offsetWidth+5){l=oMark.offsetWidth-oFloat.offsetWidth+5;} if(t<-5) { t=-5; } else if (t>oMark.offsetHeight-oFloat.offsetHeight+5){t=oMark.offsetHeight-oFloat.offsetHeight+5;} oFloat.style.left=l+'px'; oFloat.style.top=t+'px'; var tempX=l/(oMark.offsetWidth-oFloat.offsetWidth); var tempY=t/(oMark.offsetHeight-oFloat.offsetHeight); document.title=tempX; oImg.style.left=-tempX*(oImg.offsetWidth-oBig.offsetWidth)+'px'; oImg.style.top=-tempY*(oImg.offsetHeight-oBig.offsetHeight)+'px'; } }; </script> </head> <body> <div id="div1"> <div class="small_pic"> <span class="mark"></span> <span class="float_layer"></span> <img src="images/01.jpg" alt="放大圖片1" style="width: 200px;"> </div> <div class="big_pic"> <img src="images/01.jpg" alt="放大圖片2"> </div> </div> </body> </html>