基於JavaScript實現放大鏡效果
描述:右側圖片必須是左側圖片的倍數大,主要是獲取鼠標相對與被觸發元素的座標位置,再通過位置定位實現效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大鏡效果</title>
<style type="text/css">
*{
margin: 0; padding: 0;
}
#left{
width: 400px; height: 400px;
background: url(./400x400.jpg) no-repeat 0 0/100% 100%;
float: left; margin-left: 20px;
position: relative;
cursor: crosshair;
}
#box{
/* 大小應該是圖片的四分之一 */
width: 200px; height: 200px;
background: rgba(0, 0, 0, 0.3);
position: absolute; top: 0; left: 0;
display: none;
}
#cover{
width: 400px; height: 400px;
background: rgba(0, 0, 0, 0);
position: absolute; top: 0; left: 0;
}
#right{
width: 400px; height: 400px;
float: left; margin-left: 20px;
position: relative;
overflow: hidden;
display: none;
}
#pic{
position: absolute; top:0; left:0;
}
</style>
<script>
window.onload = function(){
// 給left元素綁定鼠標移動事件
var left = document.getElementById("left");
var box = document.getElementById("box");
var right = document.getElementById("right");
left.onmousemove = function(event){
// 獲取事件對象
var ev = window.event || event;
// 獲取鼠標與元素的位置,相對於被觸發的元素left左上角位置
var m_left = ev.layerX || ev.offsetX;
var m_top = ev.layerY || ev.offsetY;
// document.title = (m_left + "|" + m_top);
// 計算box的位置
var box_left = m_left-100;
var box_top = m_top-100;
document.title = (box_left + "|" + box_top);
// 設置box移動條件
box_left = box_left<0?0:box_left;
box_top = box_top<0?0:box_top;
box_left = box_left>200?200:box_left;
box_top = box_top>200?200:box_top;
// 讓box動起來
box.style.left = box_left + "px";
box.style.top = box_top + "px";
// 讓右邊圖片動起來
pic.style.left = "-" + box_left*2 + "px";
pic.style.top = "-" + box_top*2 + "px";
};
// 鼠標移入圖片顯示
left.onmouseover = function(){
box.style.display = "block";
right.style.display = "block";
};
// 鼠標移出事件
left.onmouseout = function(){
box.style.display = "none";
right.style.display = "none";
};
}
</script>
</head>
<body>
<!-- 左邊圖片 -->
<div id="left">
<!-- 鋪抓圖片的表框 -->
<div id="box"></div>
<!-- 遮罩層 -->
<span id="cover"></span>
</div>
<!-- 右邊圖片,該圖片應該是左邊圖片的倍數大 -->
<div id="right">
<img src="./800x800.jpg" width="800" id="pic">
</div>
</body>
</html>