Javascript仿京东放大镜的效果
632855323gjp 人气:0随便找一个图片吧。小伙伴们,想怎么玩就怎么玩(注意路径),亲自测试,绝对没问题。
话不多说,请看代码:
<html> <head> <meta charset="utf-8"> <style type="text/css"> body,div{margin: 0; padding: 0;} #zhuti{ margin:50px; position: relative; } #small{ width: 300px; height: 187px; border: 1px solid #000; } #big{ border: 1px solid #666; overflow: hidden; width: 300px; height: 187px; position: absolute; left: 310px; top: 0px; display: none; /*默认隐藏*/ } #jingtou{ width: 50px; height: 50px; background: #666; opacity: 0.4; position: absolute; display: none; /*默认隐藏*/ } #bigimg{ position: absolute; } </style> </head> <body> <div id="zhuti"> <div id="small"> <div id="jingtou"></div> <img src="img/ktm_small.jpg"> </div> <div id="big"> <img src="img/ktm_big.jpg" id="bigimg"> </div> </div> <script type="text/JavaScript"> //封装一个函数(id形式参数) function $(id) { return document.getElementById(id); } var small =$('small'); var big =$('big'); var jingtou =$('jingtou'); var zhuti =$('zhuti'); var bigimg =$('bigimg'); //监视鼠标(镜头) small.onmouseover = function(){ big.style.display='block'; jingtou.style.display='block'; } small.onmouseout = function(){ big.style.display='none'; jingtou.style.display='none'; } //挡鼠板移动的时候 small.onmousemove = function(event){ //获得当前坐标 //减去镜头宽度的一半 var left = event.clientX - zhuti.offsetLeft -jingtou.offsetWidth/2; var top = event.clientY -zhuti.offsetTop - jingtou.offsetHeight/2; //进行判断语句(固定0的位置) //向左走 if(left<=0){ left =0; } //向上走 if(top<=0){ top =0; } //向右走 if(left >= small.offsetWidth-jingtou.offsetWidth){ left = small.offsetWidth-jingtou.offsetWidth; } //向下走 if(top >= small.offsetHeight-jingtou.offsetHeight){ top = small.offsetHeight-jingtou.offsetHeight; } //小图的比例 var smallX = left / (small.offsetWidth - jingtou.offsetWidth); //var smallX = left / (small.offsetWidth - jingtou.offsetWidth); var smallY = top / (small.offsetHeight - jingtou.offsetHeight); //var smallY = top / (small.offsetHeight - jingtou.offsetHeight); var bigX = -smallX * (bigimg.offsetWidth - big.offsetWidth); var bigY = -smallY * (bigimg.offsetHeight - big.offsetHeight); //求a和b的值 bigimg.style.left = bigX + 'px'; bigimg.style.top = bigY + 'px'; //镜头距离左边的位置==鼠标距离左边的位置 jingtou.style.left = left +'px'; jingtou.style.top = top +'px'; } </script> </body> </html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
加载全部内容