1. 程式人生 > >一個移入遮罩層消失的放大鏡

一個移入遮罩層消失的放大鏡

具體的實現效果如上圖,即滑鼠移入時遮罩層消失

實現原理:背景圖和遮罩層不進行任何操作,保持最初狀態就好,然後給移動的小方塊加和大的背景圖一樣的背景圖,移動小方塊的同時通過background-position移動小方塊背景圖的位置來實現

老規矩,直接上程式碼,感興趣的同學可以拉下去自己看看

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"
> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #box{ width: 350px; height: 350px; margin: 50px; border: 1px solid #000; position: relative; /* overflow: hidden;
*/ } #mask{ width: 175.5px; height: 175.5px; background: url(1122.png) ; position: absolute; top: 0; left: 0; display: none; cursor: move; } #big{ position: absolute
; top: 0; left: 355px; width: 400px; height: 400px; overflow: hidden; display: none; border: 1px solid #000; } #bImg{ position: absolute; width: 800px; height: 800px; top: 0; left: 0; } #zzc{ width: 350px; height: 350px; background: grey; opacity: .3; position: absolute; top: 0; left: 0; overflow: hidden; } #small{ overflow: hidden; height: 100%; } </style> </head> <body> <div id="box"> <div id="small"> <img src="1122.png" id="sImg"> <div id="zzc"></div> <div id="mask"></div> </div> <div id="big"> <img src="1122.png" id="bImg"> </div> </div> </body> </html> <script> function $id(id){ return document.getElementById(id); } var box = $id("box"); var small = $id("small"); var sImg = $id("sImg"); var mask = $id("mask"); var big = $id("big"); var bImg = $id("bImg"); var zzc = $id("zzc"); // 滑鼠移入事件 small.onmouseover = function() { mask.style.display = "block"; big.style.display = "block"; } //滑鼠移出事件 small.onmouseout = function() { mask.style.display = "none"; big.style.display = "none"; } //滑鼠移動 small.onmousemove = function(e){ var e = e || event; var x= e.pageX - box.offsetLeft - mask.offsetWidth/2; var y= e.pageY - box.offsetTop - mask.offsetHeight/2; var maxL = box.offsetWidth - mask.offsetWidth; var maxT = box.offsetHeight - mask.offsetHeight; x = x < 0 ? 0 :(x > maxL ? maxL : x); y = y < 0 ? 0 :(y > maxT ? maxT : y); mask.style.left = x + "px"; mask.style.top = y + "px"; //mask背景圖位置 mask.style.backgroundPosition = -x + "px -" + y +"px"; //最終的比例關係是這樣的: //大圖寬度/小圖寬度 = 大圖可視區big寬度/小圖可視區mask寬度 = 大圖向左移動距離 / // mask向右移動的距離 var bigx = x * bImg.offsetWidth / sImg.offsetWidth; var bigy = y * bImg.offsetHeight / sImg.offsetHeight; bImg.style.left = -bigx +"px"; bImg.style.top = -bigy +"px"; } </script>

 

好了,就寫到這裡了,我要繼續去喝枸杞了,補身體重要,聽說紅枸杞紅枸杞黃芪一起泡快樂似神仙,也不知道真假