js-淘宝放大镜

 如图所示:通过左图中移动区域块在右图中显示该区域大图,也就是放大镜效果

设计思路:首先需要两张内容一样,尺寸大小成一定比例的一张大图和小图,然后将这两个图分别放入创建的盒模型中,左边为小盒子装着小图片,右边为大盒子装着大图片,在左边的盒子中创建点击事件,设置鼠标值,然后将鼠标值以一定比例赋值给右边大盒子中大图片所对应的边距

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            box-sizing: border-box;
            padding: 0;
            margin: 0;
        }
        .smallBox{
            position: relative;
            float: left;
            border: 1px solid black;
            margin: 100px 50px;
        }
        .smallBox img{
            width: 400px;
            height: 225px;
            display: block;
        }
        .bigBox{
            float: left;
            width: 720px;
            height: 450px;
            border: 1px solid blue;
            overflow: hidden;
            position: relative;
        }
        .bigBox img{
            position: absolute;
        }
        .move{
            position:absolute ;
            width: 90px;
            height: 90px;
            background-color: rgba(233,24,230,.5);
        }
    </style>
</head>
<body>
<script src="getELement.js"></script>
<div class="smallBox">
    <img  src="images/图片8.jpg" alt="" id="smallPic">
    <div class="move" style="left: 0; top: 0;"></div>
    <!--阴影块-->
</div>
<div class="bigBox">
    <img src="images/图片7.jpg" alt="" id="bigPic" style="left: 0;top: 0">
</div>
<script>
    window.onload = function () {
        var smallBox = my$1('.smallBox')
        var move = my$1('.move')
        var bigBox = my$1('.bigBox')
        var bigPic = my$1('#bigPic')
        var smallPic = my$1('#smallPic')
        //1:鼠标在小盒子上发生移动 move随着鼠标移动
        smallBox.onmousemove = function (e) {
            this.style.cursor = 'move'
            var newLeft = e.clientX - smallBox.offsetLeft - move.offsetWidth/2
            var newTop = e.clientY - smallBox.offsetTop - move.offsetTop/2
            /*先判断在赋值*/
            //左边界
            if (newLeft<0){
                newLeft = 0;
            }
            //右边界
            if (newLeft > smallBox.offsetWidth - move.offsetWidth) {
                newLeft = smallBox.offsetWidth - move.offsetWidth
            }
            //上边界
            if (newTop < 0){
                newTop = 0;
            }
            //下边界
            if (newTop > smallBox.offsetHeight - move.offsetHeight) {
                newTop = smallBox.offsetHeight - move.offsetHeight
            }
            move.style.left = newLeft + 'px'
            move.style.top = newTop + 'px'
            /*一开始就设置小盒子宽度/大盒子宽度 = 小照片宽度/大照片宽度*/
            var bill = smallBox.offsetWidth/bigBox.offsetWidth;
            //比例:小图的宽度/大图的宽度

            bigPic.style.left = -newLeft/bill + 'px'
            bigPic.style.top = -newTop/bill + 'px'

        }
        //2:控制移动范围 上下左右移动
        //3;move块移动的距离去换算大图标移动距离 赋值给大图
    }
</script>
</body>
</html>

最终的效果图是:

猜你喜欢

转载自blog.csdn.net/weixin_44239541/article/details/88204741