原生JS實現放大鏡功能
阿新 • • 發佈:2018-11-19
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { padding: 0; margin: 0; } img { vertical-align: middle; } .box { margin: 100px; width: 350px; height: 467px; padding: 1px; border: 1px solid yellow; position: relative; } .box .small { width: 350px; position: relative; } .box .small .mask { width: 160px; height: 160px; background-color: yellow; -webkit-filter: opacity(40%); position: absolute; left: 0; top: 0; display: none; } .box .big { position: absolute; left: 360px; top: 0; width: 400px; height: 400px; overflow: hidden; display: none; border: 1px solid red; } .box .big img { left: 0; top: 0; position: absolute; } </style> </head> <body> <div class="box" id="box"> <div class="small" id="small"> <img src="images/small.jpg" alt="" > <div id="mask" class="mask"></div> </div> <div id="big" class="big"> <img src="images/big.jpg" alt="" /> </div> </div> <script src="js/moon.js"></script> <script> //獲取box var box=my$('box'); //獲取小圖框,大圖框 var small=box.children[0]; var big=box.children[1]; //獲取大圖 var bigImg=big.children[0]; //獲取mask var mask=small.children[1]; //滑鼠放入box,mask和big顯示,移開消失 box.onmouseover=function(e){ mask.style.display='block'; big.style.display='block'; this.style.cursor='move'; }; box.onmouseout=function(){ mask.style.display='none'; big.style.display='none'; }; small.onmousemove=function(e){ //獲取滑鼠的可是區域座標 var x=e.clientX-mask.offsetWidth/2; var y=e.clientY-mask.offsetHeight/2; x=x-100; y=y-100; // console.log(x+'---'+y); //設定滑鼠不能移出small相框 x=x>0?x:0; x=x<small.offsetWidth-mask.offsetWidth?x:small.offsetWidth-mask.offsetWidth; y=y>0?y:0; y=y>small.offsetHeight-mask.offsetHeight?small.offsetHeight-mask.offsetHeight:y; //設定mask跟隨滑鼠移動 mask.style.marginLeft=x+'px'; mask.style.marginTop=y+'px'; //遮擋層的移動距離/大圖的移動距離=遮擋層的最大移動距離/大圖的最大移動距離 //大圖的移動距離=遮擋層的移動距離*大圖的最大移動距離/遮擋層的最大移動距離 //大圖的橫向的最大移動距離 var maxX = bigImg.offsetWidth - big.offsetWidth; //大圖的縱向的最大移動距離 //var maxY = bigImg.offsetHeight - big.offsetHeight; //大圖的橫向移動的座標 var bigImgMoveX = x * maxX / (small.offsetWidth - mask.offsetWidth); //大圖的縱向移動的座標 var bigImgMoveY = y * maxX / (small.offsetWidth - mask.offsetWidth); //設定圖片移動 bigImg.style.marginLeft = -bigImgMoveX + "px"; bigImg.style.marginTop = -bigImgMoveY + "px"; }; </script> </body> </html>
其中引入的moon.js程式碼如下:
//通過id獲取元素
function my$(id){
return document.getElementById(id);
}
整個專案的壓縮包百度網盤地址為:https://pan.baidu.com/s/1sJS2-k-j8GubC6nINsfnLA
提取碼為:gihn