Javascript仿京东放大镜的效果
程序员文章站
2023-12-04 08:25:46
随便找一个图片吧。小伙伴们,想怎么玩就怎么玩(注意路径),亲自测试,绝对没问题。
话不多说,请看代码:
...
随便找一个图片吧。小伙伴们,想怎么玩就怎么玩(注意路径),亲自测试,绝对没问题。
话不多说,请看代码:
<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>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!