编程语言
首页 > 编程语言> > JavaScript放大镜案例

JavaScript放大镜案例

作者:互联网

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<style type="text/css">
    * {
        margin: 0;
        padding: 0;
    }

    #box {
        width: 350px;
        height: 350px;
        border: 1px solid #000;
        margin: 200px;
        position: relative;
    }

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

    #mask {
        width: 175px;
        height: 175px;
        background: black;
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0.3;
        display: none;
        cursor: move;
    }

    #small {
        position: relative;
    }

    #bigImg {
        position: absolute;
        left: 0;
        top: 0;
    }
</style>

<body>
    <div id="box">
        <div id="small">
            <!--小图区-->
            <img src="images/001.jpg" alt="" />
            <div id="mask"></div>
            <!--遮罩层-->
        </div>
        <div id="big">
            <!--大图区-->
            <img src="images/0001.jpg" alt="" id="bigImg" />
        </div>
    </div>
</body>

</html>
<script type="text/javascript">
    // 获取dom对象
    var $box = document.querySelector('#box');
    var $mask = document.querySelector('#mask');
    var $big = document.querySelector('#big');
    var $bigImg = document.querySelector('#bigImg');

    // 鼠标移入
    $box.onmouseenter = function (e) {
        e = e || window.event;
        $mask.style.display = 'block';
        $big.style.display = 'block';
        // 遮罩层的最大移动距离
        var maxX = $box.clientWidth - $mask.offsetWidth,
            maxY = $box.clientHeight - $mask.offsetHeight;
        // 获取box的偏移量
        var left = $box.offsetLeft,
            top = $box.offsetTop;
        // 鼠标移动
        document.onmousemove = function (e) {
            e = e || window.event;
            // 87.5是阴影块的一半,为了让鼠标居中
            var moveX = e.pageX - left - 87.5;
            moveY = e.pageY - top - 87.5;
            if (moveX < 0) {
                moveX = 0;
            } else if (moveX > maxX) {
                moveX = maxX;
            }
            if (moveY < 0) {
                moveY = 0;
            } else if (moveY > maxY) {
                moveY = maxY;
            }
            $mask.style.left = moveX + 'px';
            $mask.style.top = moveY + 'px';
            // 大图片是小图片的两倍 所以×2
            $bigImg.style.left = -2 * moveX + 'px';
            $bigImg.style.top = -2 * moveY + 'px';
        }
    }
    // 鼠标离开 隐藏大图区和遮罩层
    $box.onmouseleave = function () {
        $mask.style.display = 'none';
        $big.style.display = 'none';
    }
</script>

 

 

 

 

两张图传这了

标签:box,style,放大镜,top,JavaScript,mask,moveX,案例,var
来源: https://www.cnblogs.com/H-Y-Z/p/10542211.html