原生js实现跑马灯(走马灯)效果

要求:

    跑马灯: 
    创建两个大盒子对象,让小盒子在大盒子持续按规律进行移动
    1、点击“开始”按钮,开始移动
    2、点击“停止按钮”,结束移动

 静态布局:

 <div class="big">
        <div class="small"></div>
    </div>
    <button>开始</button>
    <button>结束</button>

css样式:

<style>
        * {
            margin: 0;
            padding: 0;
        }

        .big {
            width: 500px;
            height: 300px;
            border: 1px solid black;
            margin: 20px;
            position: relative;
        }

        .small {
            width: 50px;
            height: 50px;
            background-color: skyblue;
            position: absolute;
        }

        button {
            margin-right: 5px;
            margin-left: 20px;
        }
    </style>

 静态效果:

 js代码:

<script>
        //获取元素
        var button = document.querySelectorAll("button")
        var bigbox = document.querySelector(".big")
        var smallbox = document.querySelector(".small")
        var dsq;
        //给按钮“开始”绑定事件
        button[0].onclick = function () {
            dsq = setInterval(function () {
                //获取small的偏移量
                var left1 = smallbox.offsetLeft
                var top1 = smallbox.offsetTop
                //获取small的移动最大值,减2为边框多出的2px
                var maxX = bigbox.offsetWidth - smallbox.offsetWidth - 2
                var maxY = bigbox.offsetHeight - smallbox.offsetHeight - 2
                //分析情况
                //small往右走
                if (left1 < maxX && top1 == 0) {
                    smallbox.style.left = left1 + 10 + 'px'
                    left1 = smallbox.style.left
                }
                //small往下走
                else if (top1 < maxY && left1 == 450) {
                    smallbox.style.top = top1 + 10 + 'px'
                    top1 = smallbox.style.top
                }
                //small往左走
                else if (top1 > 0 && left1 > 0) {
                    smallbox.style.left = left1 - 10 + 'px'
                    left1 = smallbox.style.left
                    //small往上走
                } else if (left1 == 0) {
                    smallbox.style.top = top1 - 10 + 'px'
                    top1 = smallbox.style.top
                }
                //100毫秒回调一次
            }, 100)
        }
        //给结束按钮设置点击事件,当点击时,则清除定时器
        button[1].onclick = function () {
            clearInterval(dsq)
        }

实现的效果: 

跑马灯

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值