原生js放大鏡
步驟寫在注釋裡,新手。
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css" media="screen">
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:100%;
width:100%;
}
#lay{
background:#fff;
border:1px solid gray;
position: absolute;
top:0;
left: 0;
opacity:0.5;
display:none;
filter:alpha(opacity=50);
}
</style>
</head>
<body>
<div id="Box">
<!-- 圖檔 -->
<img src="jietu.png" height="345" width="340"/>
<span id="lay"></span>
</div>
<div id="bigBox">
<!-- 圖檔 同上相同-->
<img src="jietu.png" height="345" width="340" />
</div>
<script>
function fdj(scale){
//擷取元素
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;//事件源的相容問題
this.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;
}
fdj(2);
</script>
</body>
</html>