简单实现js放大镜效果
程序员文章站
2022-09-02 14:54:38
本文实例为大家分享了js放大镜效果展示的具体代码,供大家参考,具体内容如下
具体代码如下:
本文实例为大家分享了js放大镜效果展示的具体代码,供大家参考,具体内容如下
具体代码如下:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>document</title> <style> body,div,img{ margin:0; padding:0; } img{ display:block; border:none; } #box{ position:absolute; top:20px; left:20px; width:350px; height:350px; box-shadow:3px 3px 10px 0 #111111; } #box img{ width:100%; height:100%; } #mark{ display:none; position:absolute; top:0; left:0; width:175px; height:175px; background:#000; opacity: 0.5; filter:alpha(opacity=50); cursor:move; } #boxright{ display:none; position:absolute; top:20px; left:380px; width:350px; height:350px; overflow:hidden; } /*我们右侧的图片的大小是需要严格计算的: mark的width是box的width的一半,那么我们的大图宽度也应该是小图的二倍 */ #boxright img{ position:absolute; top:0; left:0; width:200%; height:200%; } </style> </head> <body> <div id='box'> <img src="img/iphone.jpg" alt=""> <div id='mark'></div> </div> <div id='boxright'> <img src="img/iphone_big.jpg" alt=""> </div> <script> //放大镜的原理: 我们的mark横向是box的一半,纵向也是box的一半,那么右侧的大图横向(纵向)应该是左侧小图的2倍 var box = document.getelementbyid('box'); var mark = document.getelementbyid('mark'); var boxright = document.getelementbyid('boxright'); //设置mark这个盒子 function setposition(e){ var top = e.clienty - box.offsettop - (mark.offsetheight/2); var left = e.clientx - box.offsetleft - (mark.offsetwidth/2); //边界判断 var templ = 0,tempt = 0; var minl = 0,mint = 0,maxl = box.offsetwidth - mark.offsetwidth,maxt = box.offsetheight - mark.offsetheight ; if(left<minl){ mark.style.left = minl + "px"; templ = minl; }else if(left>maxl){ mark.style.left = maxl + "px"; templ = maxl; }else{ mark.style.left = left + "px"; templ = left; } if(top<mint){ mark.style.top = mint + "px"; tempt = mint; }else if(top>maxt){ mark.style.top = maxt + "px"; tempt = maxt; }else{ mark.style.top = top + "px"; tempt = top; } //右侧图片跟着运动:左侧移动多少,右侧跟着移动他的2倍即可 var oimg = boxright.getelementsbytagname("img")[0]; oimg.style.left = -templ*2 + "px"; oimg.style.top = -tempt*2 + "px"; } box.onmouseenter = function(e){ e = e || window.event; mark.style.display = "block"; setposition(e); boxright.style.display = "block"; } box.onmousemove = function(e){ e = e || window.event; setposition(e); } box.onmouseleave = function(e){ e = e || window.event; mark.style.display = "none"; boxright.style.display = "none"; } </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 为vue项目自动设置请求状态的配置方法