JS实现抽奖效果

这种效果很常见,所以对我们前段开发者来说是基本功,必须掌握.

页面布局:

实现思路如图:(一条流水线的思路)

代码也很简单啦

HTML部分:

<body>
<div id="box">
<input type="button" value="开始抽奖" id="start">
<input type="button" value="停止抽奖" id="end">
</div>
<img src="01.jpg" alt="" id="picture">
</body>

CSS部分:

 <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        #picture{
            margin: 25px auto;
            width: 400px;
            height:200px;
            display: block;
        }
        #box{
            width: 300px;
            height: 70px;
            margin: 30px auto;

            /*background-color: yellow;*/

        }
        #box input{
            width: 100px;
            height: 30px;
            /*margin: 10px;*/
            margin-top:20px;
            margin-right: 20px;

        }
    </style>

JS部分:

<script>
        var timer;
        window.onload = function () {
            var start = document.getElementById('start');
            var end = document.getElementById('end');
            var picture = document.getElementById('picture');
            //用来存储图片路径的数组
            var picarr = ['01.jpg', '02.jpg', '03.jpg',
                '04.jpg', '05.jpg', '06.jpg', '07.jpg',
                '08.jpg'];
            //给按钮加单击事件
            clearInterval(timer);
            start.onclick = function () {
                //设置定时器,每隔一秒换一张图片
                timer = setInterval(function () {
                    //抽取数组随机下标
                    var num = Math.floor(Math.random() * (picarr.length - 1 + 1 - 0) + 0);
                    //将抽到的图片路径给图片元素
                    picture.setAttribute('src', picarr[num]);
                }, 1000)
            }
            //给停止按钮加单击事件
            end.onclick = function () {
                clearInterval(timer);
            }
        }
</script>

猜你喜欢

转载自blog.csdn.net/lishundi/article/details/81409054