时间:2021-07-01 10:21:17 帮助过:9人阅读
本文实例为大家介绍了基于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放大镜效果有所帮助。