网页图片放大镜

基本思路:大图片盒子包裹大图片,小图片盒子包裹小图片,遮盖层位于小图片盒子里,用鼠标的移动事件,让遮盖层跟随鼠标移动,移动遮盖层的同时让大图片跟着移动相应比例的距离,注意大图片移动的方向和遮盖层的方向相反,难点为获取相应距离

1.html代码

<body>
    <div class="container">
        <div class="smallbox">
            <img src="./images/small.jpg" class="smallimg">
            <div class="mask"></div>
        </div>
        <div class="bigbox">
            <img src="./images/big.jpg" class="bigimg">
        </div>
    </div>
</body>

2.css代码

*{
    margin: 0;
    padding: 0;
}
.container{
    width: 800px;
    height: 700px;
    margin: 50px auto;
    display: flex;//flex布局让两个盒子并排
}
.smallbox{
    width: 300px;
    height: 450px;
    border: 1px solid;
    position: relative;
}
.smallimg{
    width: 100%;
    height: 100%;
}
//遮盖层
.mask{
    width: 100px;//宽高为小图片的三分之一,这意味着大图片移动的比例也应该是三比一
    height: 150px;
    background-color: #bfa;
    position: absolute;
    opacity: .5;
    display: none;
}
.bigbox{
    width: 350px;
    height: 405px;
    overflow: hidden;//超出大图片盒子部分的图片隐藏(看起来就像放大镜了)
    display: block;
    position: relative;
    border: 1px solid;
} 
.bigimg{
    width: 870px;
    height: 1310px;
    position: absolute;
}

js代码

window.onload = function () {
  var smallBox = document.querySelector(".smallbox");
  var mask = document.querySelector(".mask");
  var bigBox = document.querySelector(".bigbox");
  var bigImg = document.querySelector(".bigimg");
  var container = document.querySelector(".container");
  //鼠标移入移出小盒子控制大盒子和遮盖层的显示与隐藏
  smallBox.onmouseover = function () {
    mask.style.display = "block";
    bigBox.style.display = "block";
  };
  smallBox.onmouseout = function () {
    mask.style.display = "none";
    bigBox.style.display = "none";
  };
  smallBox.onmousemove = function (e) {
    //求出鼠标在盒子中的坐标,公式:鼠标在页面的坐标-大盒子距离页面左侧的距离-遮盖层自身宽度的一半(鼠标在遮盖层中居中)
    var x = e.clientX - container.offsetLeft-mask.offsetWidth/2;
    var y = e.clientY - container.offsetTop-mask.offsetHeight/2;
    //求出遮盖层在小图片盒子中的最大移动距离,公式:小图片盒子的宽度-遮盖层的宽度
    var x_move =smallBox.offsetWidth-mask.offsetWidth
    var y_move =smallBox.offsetHeight-mask.offsetHeight
    //if判断来设置遮盖层不能跑到小图片盒子外面
    if(x>=x_move){
        x=x_move
    }else if(x<0){
        x=0
    }
    if(y>=y_move){
        y=y_move
    }else if(y<0){
        y=0
    }
    //设置遮盖层移动的距离
    mask.style.left = x  + "px";
    mask.style.top = y + "px";
    //设置大图片移动的距离
    bigImg.style.left=-3*x+"px"
    bigImg.style.top=-3*y+"px"
  }; 
};

看起来绕,但原理其实挺简单的,拿到相应移动距离以后进行赋值就行了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值