基于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>