js之页面滚动,使用js控制的小火箭滚动页面

 

火箭飞行, 屏幕联动 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>火箭</title>
</head>

<body>
    <div style="width: 50px;height:50px;background-color: #f00;">

    </div>
    <div style="height: 1900px;border-left: 1px solid #ccc;margin-left: 20px;">
        <div style="height: 50px;border-left: 200px solid #00f;margin-left: 60px;">
            四楼风景
        </div>
        <div style="height: 50px;border-left: 200px solid #33f;margin-left: 60px;margin-top: 400px;">
            三楼风景
        </div>
        <div style="height: 50px;border-left: 200px solid #66f;margin-left: 60px;margin-top: 400px;">
            二楼风景
        </div>
        <div style="height: 50px;border-left: 200px solid #99f;margin-left: 60px;margin-top: 400px;">
            一楼风景
        </div>
    </div>
    <div id="test_rocket"
        style="position: absolute;top:1700px;">
        <div style="width: 0px;
                    height: 0px;
                    border-left: 30px solid #fff;
                    border-bottom: 30px solid #f00;
                    border-right: 30px solid #fff;
                    border-top: 30px solid #fff;"></div>
        <div style="height: 100px;width:60px;background-color: #f00;;"></div>
    </div>
    <input type="button" value="返回顶部" id="btn"
        style="margin-bottom: 50px;">
</body>
<script>
    window.onload = function () {
        var rocket = document.querySelector("#test_rocket");
        document.querySelector("#btn").onclick = function () {
            rocket.style.top = "1700px";//设置火箭的默认位置
            var n = parseInt(rocket.style.top.split("px")[0]);
            let a2,a1 = setInterval(() => {
                rocket.style.top = n + "px";
                n -= 30;//每次移动的距离
                //火箭距离顶部小于0, 不再继续移动火箭, 清除定时器
                if(parseInt(rocket.style.top.split("px")[0])<0){
                    clearInterval(a1)
                    clearInterval(a2)
                }
            }, 10);
            //屏幕位置的移动, 靠这个移动屏幕, 实现最终的随着火箭移动屏幕也移动(所谓的联动)
            a2 = setInterval(() => {
                if(window.pageYOffset>parseInt(rocket.style.top.split("px")[0])){
                    document.documentElement.scrollTop = rocket.style.top.split("px")[0];
                }
            }, 10)
        };
    }
</script>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值