本文實例為大家介紹了基於javascript實現放大鏡效果的原理和程式碼,分享給大家供大家參考,具體內容如下:
原理:
A:放大鏡 B:小圖片
C:大圖片可視區域
D:大圖
滑鼠的位置應該在放大鏡的中央,所以滑鼠位置為:
clientX=A.offsetLeft()+B.offsetLeft+1/2*A.offsetWidth;
clientY=A.offsetTop()+B.offsetTop+1/2*A.offsetHeight;
滑鼠移動過程中:放大鏡A和大圖D是一起隨滑鼠成比例運動的,因為當放大鏡A的右邊框移動到與小圖B的右邊框重合時,大圖D也應該移動到了右邊框與C的右邊框重合的地方,所以,他們的移動比例是:(D.offsetWidth-C.offsetWidth)/(B.offsetWidth-A.offsetWidth)=b/a
HTML部分:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>放大镜效果</title> <style> *{ margin:0; padding:0; } #demo{ position: relative; margin:30px 50px; width: 1000px; height: 600px; border: 1px solid #000; } #zhezhao{ position: absolute; z-index:2; background:red; width:402px; height:402px; left: 20px; top:20px; opacity: 0; } #small{ position: absolute; width:402px; height:402px; left: 20px; top:20px; border: 1px solid #000; z-index: 1; } #small img{ position: absolute; } #big{ position: relative; top: 20px; left: 460px; width:500px; height:500px; border: 1px solid #000; overflow: hidden; display: none; z-index: 1; } #big img{ position: absolute; } #glass{ position: absolute; width:100px; height: 100px; opacity: 0.3; background:orange; display: none; } </style> </head> <body> <div id='demo'> <div id='zhezhao'> </div> <!-- 在ie浏览器中,当鼠标在放大镜上是,浏览器并不认为鼠标同样在小图的div上,所以加个遮罩层 兼容ie--> <div id='small'> <img src='images/small.png' alt=''> <div id='glass'></div> </div> <div id='big'> <img src='images/big.jpg' alt='' > </div> </div> </body> </html>
js部分:
<script> window.onload=function(){ var demo =document.getElementById('demo'); var small =document.getElementById('small'); var big =document.getElementById('big'); var glass =document.getElementById('glass') var image =document.getElementById('big').getElementsByTagName('img')[0]; var zhezhao=document.getElementById('zhezhao'); zhezhao.onmouseover=function(){ glass.style.display='block' big.style.display='block' } zhezhao.onmouseout=function(){ glass.style.display='none' big.style.display='none' } //弄清楚clientX,offsetLeft,left的关系,注意区分 zhezhao.onmousemove=function(ev){ var event=ev var left=event.clientX-demo.offsetLeft-small.offsetLeft-glass.offsetWidth/2; var top =event.clientY-demo.offsetTop -small.offsetTop -glass.offsetHeight/2; if(left<0){ left=0; }else if(left>(small.offsetWidth-glass.offsetWidth)){ left=small.offsetWidth-glass.offsetWidth } if(top<0){ top=0; }else if(top>(small.offsetHeight- glass.offsetHeight)){ top=small.offsetHeight- glass.offsetHeight } glass.style.left =left+'px'; glass.style.top =top+'px'; var percent=(image.offsetWidth-big.offsetWidth)/(small.offsetWidth-glass.offsetWidth) image.style.left=-percent*left+'px' image.style.top =-percent*top+'px' } } </script>
以上就是本文的全部內容,希望對大家實現javascript放大鏡效果有所幫助。