JS之放大镜效果

JS之放大镜效果

哈喽小伙伴们,今天给大家分享的是我制作的一个简易放大镜效果案例,对,没错,就是仿照的电商网站的商品放大镜展示效果,下面我们来看具体的代码:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>JS之放大镜效果</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
             350px;
            height: 350px;
            margin: 100px;
            border: 1px solid #ccc;
            position: relative;
        }

        .big {
             400px;
            height: 400px;
            position: absolute;
            top: 0;
            left: 360px;
            border: 1px solid #ccc;
            overflow: hidden;
            display: none;
        }

        .mask {
             175px;
            height: 175px;
            background: rgba(255, 255, 0, 0.4);
            position: absolute;
            top: 0px;
            left: 0px;
            cursor: move;
            display: none;
        }

        .small {
            position: relative;
        }

    </style>
</head>
<body>
<div class="box" id="box">
    <div class="small"><!--小层-->
        <img src="images/small.png" width="350" alt=""/>
        <div class="mask"></div><!--遮挡层-->
    </div>
    <div class="big"><!--大层-->
        <img src="images/big.jpg" width="800" alt=""/><!--大图-->
    </div>
</div>

<script>
//    封装获取ID的函数
    function my$(id){
        return document.getElementById(id);
    };
//    获取盒子
    var box = my$("box");
//    获取小层
    var small = my$("box").children[0];
//    获取大层
    var big = my$("box").children[1];
//    获取大层中的img
    var img = big.children[0];
//    获取遮罩层
    var mask = small.children[1];

//    鼠标放到小层上触发的事件
    small.onmouseover=function(){
        mask.style.display="block";
        big.style.display="block";
//        鼠标拖动事件
        small.onmousemove=function(e){
//            计算遮罩层的移动坐标    当前坐标-margin值-遮罩层的一半
            var left = e.clientX-mask.offsetWidth/2-100;
            var top = e.clientY-mask.offsetHeight/2-100;
//            上下左右加限制
//            最小移动距离为0
            left = left<0?0:left;
            top = top<0?0:top;
//            最大移动距离为小层的宽度与遮罩层宽度之差
            left = left>small.offsetWidth-mask.offsetWidth?small.offsetWidth-mask.offsetWidth:left;
            top = top>small.offsetHeight-mask.offsetHeight?small.offsetHeight-mask.offsetHeight:top;
//            让遮罩层移动相应的距离
            mask.style.left=left+"px";
            mask.style.top=top+"px";

//            放大镜中的大图按比例移动
            img.style.marginLeft=-left*(img.offsetWidth/small.offsetWidth)+"px";
            img.style.marginTop=-top*(img.offsetHeight/small.offsetHeight)+"px";
        };
    };
</script>
</body>
</html>
怎么样,是不是感觉很简单呢,这里呢没有帮大家上传具体的实现效果图,感兴趣的小伙伴可以尝试下,只需准备两张一大一下的图片即可,那么大家如果感觉代码很零散或者感觉不能灵活使用,大家可以尝试将这段代码封装一下,之后就可以当做一个小插件使用了。
原文地址:https://www.cnblogs.com/x1024/p/6006223.html