JavaScript写放大镜效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#middle {
width: 400px;
height: 400px;
position: absolute;
top : 50px;
left : 100px;
border: 1px solid;
}
#middle img {
width: 400px;
height: 400px;
}
#len {
width: 200px;
height: 200px;
background: #f00;
position: absolute;
top: 0;
left: 0;
opacity: 0.5;
display: none;
}
#big {
width: 400px;
height: 400px;
position: absolute;
top : 50px;
left : 520px;
border:1px solid;
overflow: hidden;
display: none;
}
#big img {
width: 800px;
height: 800px;
position: absolute;
top : 0;
left : 0;
}
</style>
</head>
<body>
<div id="middle">
<img src="images/middle.jpg">
<div id="len"></div>
</div>
<div id="big">
<img src="images/big.jpg" id="big_img">
</div>
<script src="js/tools.js"></script>
<script>
/* 鼠标移入/移出 div#middle */
$("#middle").onmouseenter = function(){
$("#len").style.display = "block";
$("#big").style.display = "block";
}
$("#middle").onmouseleave = function(){
$("#len").style.display = "none";
$("#big").style.display = "none";
}
// 求 div#middle 元素在文档中定位
var middleOffset = offset($("#middle"));
/* 鼠标在 div#middle 上移动 */
$("#middle").onmousemove = function(e){
// 镜头坐标
var _top = e.pageY - middleOffset.top - 100,
_left = e.pageX - middleOffset.left - 100;
// 判断镜头是否在div#middle中图范围内移动
if (_top < 0)
_top = 0;
else if (_top > 200)
_top = 200;
if (_left < 0)
_left = 0;
else if (_left > 200)
_left = 200;
// 设置镜头定位CSS
css($("#len"), {
top : _top + "px",
left : _left + "px"
});
// 设置放大图片定位
css($("#big_img"), {
top : -2 * _top + "px",
left : -2 * _left + "px"
});
}
</script>
</body>
</html>
欢迎关注微信公众号:猴哥说前端