实现淘宝放大镜效果

实现淘宝放大镜效果

首先应该清楚要实现的效果
在这里插入图片描述
然后确定图片、遮盖层的长宽,以及放大效果的长宽,然后实现遮盖层的移动,放大图片的同步,我们可以通过在图片中的半径来计算,下面贴下代码

<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">
    <style>
    #box{
        margin : 50px 100px;
        width: 600px;
        height: 400px;
    }
    #img{
        position: relative;
        width: 200px;
        height: 200px;
        margin-top: 100px;
        display: inline-block;
        border: 1px solid #000;
    }
    #mask{
        position: absolute;
        width: 100px;
        height: 100px;
        background: yellow;
        opacity: 0.5;
        left: 0;
        top: 0;
        display: none;
    }
    #section{
        display: none;
        background-image: url("../assets/logo.png");
        background-repeat: no-repeat;
        background-size: 600px;
        width: 300px;
        height: 300px;
        
    }
    </style>
    <title>Document</title>
</head>
<body>
    <div id="box">
        <div id="img">
            <img src="../assets/logo.png" width="200px">
            <div id="mask"></div>
        </div>
        <div id="section">
        </div>
    </div>
    <script >
    let img = document.getElementById("img")
    let mask = document.getElementById("mask")
    let section = document.getElementById("section")
    img.onmousemove = function(e){
            mask.style.display = "block"
            section.style.display = "inline-block"
            //(鼠标的坐标 - 图片的坐标)- 遮盖层的一半 =
             鼠标在图片中的坐标  - 遮盖层的一半 =
             相对于遮盖层中心层的偏移量
            let X = e.pageX - img.offsetLeft - mask.offsetWidth/2 
            let Y = e.pageY - img.offsetTop - mask.offsetHeight/2
            //如果偏移量小于0,取0 ,大于0小于100,
            取得到的值,大于100取100,防止遮盖层溢出border
            X = X < 0? 0 : (X > img.offsetWidth - mask.offsetWidth ? img.offsetWidth - mask.offsetWidth : X)
            Y = Y < 0? 0 : (Y > img.offsetHeight - mask.offsetHeight ? img.offsetHeight - mask.offsetHeight : Y)
            mask.style.left = X + "px"
            mask.style.top = Y + "px"
            section.style.backgroundPositionX = X * -section.offsetWidth/mask.offsetWidth +"px" 
            section.style.backgroundPositionY = Y * -section.offsetHeight/mask.offsetHeight +"px" 
    }
    img.onmouseleave = function(){
        mask.style.display = "none"
        section.style.display = "none"
    }
    </script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值