js 基礎 ---實現放大鏡的效果
阿新 • • 發佈:2019-02-03
<!DOCTYPE html> <html> <head> <title>放大鏡效果</title> <meta charset="utf-8"> <style type="text/css"> body{position: relative;} *{margin: 0;padding:0;} #Box{ height:300px; width:300px; position: relative; border:1px solid gray; } #bigBox{ height:300px; width:300px; position: absolute; top:0; left:310px; overflow: hidden; display:none; border: 1px solid gray; } #Box img{ height:300px; width:300px; } #lay{ background:#fff; border:1px solid gray; position: absolute; top:0; left: 0; opacity:0.5; display:none; filter:alpha(opacity=50); } </style> <script type="text/javascript"> window.onload = function(){ var Box = document.getElementById("Box"); var bigBox = document.getElementById("bigBox"); var bigbox = getChildNodes(bigBox)[0]; var lay = document.getElementById("lay"); //滑鼠移入時,將放大鏡和bigBox顯示出來 Box.onmouseover = function(){ lay.style.display = "block"; bigBox.style.display = "block"; } //滑鼠移出時,將放大鏡和bigBox隱藏起來 Box.onmouseout = function(){ lay.style.display = "none"; bigBox.style.display = "none"; } Box.onmousemove = function(e){ e = e || event;//事件源的相容問題 var scale = 4;//圖片的放縮比例 //將滑鼠放到放大鏡的中間 var x = e.clientX - lay.offsetWidth/2; var y = e.clientY - lay.offsetHeight/2; //將放大鏡的寬高與盒子的寬高結合起來按比例放縮 lay.style.width = parseInt(Box.offsetWidth / scale )+ "px"; lay.style.height = parseInt(Box.offsetHeight / scale)+ "px"; //設定大盒子的寬高 bigbox.style.width = Box.offsetWidth * scale + "px"; bigbox.style.height = Box.offsetHeight * scale + "px"; if(x < 0){ x = 0;//左邊界的判斷,當超出時將x置為0; } //右邊界的判斷,當超出時將x置為Box的寬度減去放大鏡的寬度; if( x >= Box.offsetWidth - lay.offsetWidth){ x = Box.offsetWidth - lay.offsetWidth; } //下邊界的判斷,當超出時將y置為Box的高度減去放大鏡的高度; if( y >= Box.offsetHeight - lay.offsetHeight){ y = Box.offsetHeight - lay.offsetHeight; } if(y < 0){ y = 0;//上邊界的判斷,當超出時將y置為0; } lay.style.left = x + "px"; lay.style.top = y + "px"; //同比例放縮,大的盒子圖片的放縮比例,當小盒子向右移動的時候,大盒子向左移動同等的比例的寬高,方向是相反的 var left = lay.offsetLeft * scale; var top = lay.offsetTop * scale ; bigbox.style.marginLeft =(left * (-1)) + "px"; bigbox.style.marginTop =(top * (-1))+ "px"; } } //獲取孩子的節點 function getChildNodes(element){ var arr = []; var eList = element.childNodes; for(var i = 0;i < eList.length;i++){ if(eList[i].nodeType == 1){//過濾空白節點 arr.push(eList[i]); } } return arr; } </script> </head> <body> <div id="Box"> <img src="1.jpg"/> <span id="lay"></span> </div> <div id="bigBox"> <img src="1.jpg" /> </div> </body> </html>