实现长图效果

首先,搭架子:

        * {
            margin: 0;
            padding: 0;
        }
        
        .box {
            width: 640px;
            height: 300px;
            border: 1px solid #000;
            margin: 100px auto;
            overflow: hidden;
            position: relative;
        }
        
        .box>.top,
        .box>.bottom {
            width: 100%;
            height: 150px;
            position: absolute;
            left: 0;
            z-index: 999;
        }
        
        .box>.bottom {
            bottom: 0;
        }
        
        .box>img {
            position: absolute;
            left: 0;
            top: 0;
        }
    <div class="box">
        <div class="top"></div>
        <div class="bottom"></div>
        <img src="images/long.gif" alt="">
    </div>

其次,设计逻辑结构:

主要监听鼠标的移入移除事件:

  • 在大盒子里再放两个小盒子,并监听这两个小盒子的移入移除事件,当鼠标移入到第一个小盒子也就是上面的小盒子时图片向上滑动,反之向下滑动
  • 当鼠标移除盒子时,图片停止滑动
        //1.获取需要操作的元素
        const oTop = document.querySelector(".top");
        const oBottom = document.querySelector(".bottom");
        const oImg = document.querySelector("img");
        const oDiv = document.querySelector('.box');
        let timer = null;

        //2.获取图片和盒子的高度,计算最大偏移位
        const boxHeight = parseInt(getComputedStyle(oDiv).height);
        const imgHeight = parseInt(getComputedStyle(oImg).height);
        // console.log(boxHeight);
        // console.log(imgHeight);
        const maxOffsetY = boxHeight - imgHeight;
        // console.log(maxOffsetY);

        //2.注册监听事件
        oTop.onmouseenter = function() {
            move(-10);
        };

        oBottom.onmouseenter = function() {
            move(10);
        };

        oTop.onmouseleave = close;
        oBottom.onmouseleave = close;

        //封装移动函数
        function move(y) {

            let offsetY = parseInt(oImg.style.top) || 0;

            timer = setInterval(function() {
                offsetY = offsetY + y;
                if ((y < 0 && offsetY <= maxOffsetY) ||
                    (y > 0 && offsetY >= 0)) {
                    clearInterval(timer);
                    return;
                }
                oImg.style.top = offsetY + "px";
            }, 10);
        }

        function close() {
            clearInterval(timer);
        }

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白小白从不日白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值