您的位置:首页 > Web前端 > JavaScript

原生JS实现窗体发生滚动后,仍然能正常使用的放大镜效果

2020-02-06 23:54 302 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
.obj{
width:100%;
height:600px;
background-color: cadetblue;
}
.obj_c{
width:1280px;
height:600px;
background-color: coral;
margin:0 auto;
}
.small{
width:200px;
height:200px;
background-color: black;
float: left;
margin:20px;
position: relative;
}
.mask{
width:60px;
height:60px;
position: absolute;
background-color: rgb(255,0,0,0.2);
left:0;
top:0;
display: none;
}
.big{
width:200px;
height:200px;
background-color: black;
float: left;
overflow: hidden;
margin-top:20px;
display: none;
position: relative;
}
.big_img{
position:absolute;
top:0;
left:0;
}

</style>
</head>
<body>
<div style="width:100%;height:600px;background-color:blanchedalmond"></div>
<div class="obj">
<div class="obj_c">
<div class="small">
<img width="200" height="200" src="img/狗.png" >
<div class="mask"></div>
</div>
<div class="big">
<img class="big_img" height="600" width="600" src="img/狗.png">
</div>
</div>
</div>
<script>
var small = document.querySelector(".small");
var mask = document.querySelector(".mask"); //区域框
var big = document.querySelector(".big");  //放大后的图片框
var big_img = document.querySelector(".big_img");
small.onmouseover = function(){
//显示选择区域框
mask.style.display = "block";
//显示放大后的图片框
big.style.display="block";
document.onmousemove = function(e){
var ev= e||event;
//body向上滚动的距离
var st = document.body.scrollTop||document.documentElement.scrollTop;
//鼠标相对于small的坐标
var X = ev.clientX - small.offsetLeft;
var Y = ev.clientY+st - small.offsetTop;

//区域框跟随鼠标
//鼠标在区域框的中心
var posX = X - mask.offsetWidth/2;
var posY = Y - mask.offsetHeight/2;
//限制区域框在图片内部
var posXMax = small.offsetWidth -mask.offsetWidth  //区域框在小图X方向上移动的最大距离,最小为0
var posYMax = small.offsetHeight - mask.offsetHeight  //区域框在小图Y方向上移动的最大距离,最小为0
posX = posX<0?0:posX;
posY = posY<0?0:posY;
posX = posX>posXMax?posXMax:posX;
posY = posY>posYMax?posYMax:posY;
mask.style.left = posX + "px";
mask.style.top = posY +"px";

//放大框的图片跟随区域框的移动而移动
//区域框移动的距离/区域框移动的最大距离 = 放大框内容移动的距离/放大框内容移动的最大距离
big_img.style.left = -(posX/posXMax)*(big_img.offsetWidth-big.offsetWidth)+"px";
big_img.style.top = -(posY/posYMax)*(big_img.offsetHeight-big.offsetHeight)+"px";
}
};
small.onmouseout = function(){
//隐藏区域框
mask.style.display = "none";
//隐藏放大后的图片框
big.style.display = "none";
//销毁鼠标移动事件
document.onmousemove = null;
}
</script>
</body>
</html>
  • 点赞
  • 收藏
  • 分享
  • 文章举报
Zhang190716 发布了8 篇原创文章 · 获赞 0 · 访问量 99 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: