继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

使用回车键控制抽奖功能

缄默蜀黍ONE
关注TA
已关注
手记 7
粉丝 7
获赞 850
    本文为《DOM事件探秘》中第四章的抽奖系统代码实现,作为初学者我在这里展示如何用js实现鼠标和键盘回车键控制事件的进行。

效果图:
图片描述 图片描述
结构代码:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>抽奖</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script type="text/javascript" src="js/script.js"></script>
</head>
<body>
    <div id="title" class="title">开始抽奖了!</div>
    <div class="btns">
        <span id="play">开 始</span>
        <span id="stop">结 束</span>
    </div>

</body>
</html>

样式代码:(css/style.css)

*{
    margin:0;
    padding: 0;
}

.title{
    width: 400px;
    height: 50px;
    margin:0 auto;
    padding-top: 30px;
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    color: #f00;}

.btns{width: 190px;
    height: 30px;
    margin:0 auto;}

.btns span{display: block;
        float: left;
        width: 80px;
        height: 27px;
        line-height: 27px;
        background-color: #036;
        border:1px solid #eee;
        border-radius: 7px;
        margin-right: 10px;
        color: #fff;
        text-align: center;
        font-size: 20px;
        font-family: "微软雅黑";
        cursor: pointer;}

JavaScript脚本:(js/script.js)

var data = ["Phone5","Ipad","三星笔记本","佳能相机","惠普打印机","谢谢参与","50元充值卡","1000元超市购物卷"];//存放抽奖内容
var timer = null,//存放定时器
    flag = 0;//存放回车键状态

window.onload = function () {
    var play = document.getElementById("play"),
        stop = document.getElementById("stop");

    //开始抽奖
    play.onclick = playFun;
    //停止抽奖
    stop.onclick = stopFun;
    /**************************/
    //用键盘回车控制开始抽奖和停止抽奖
    //键盘事件“keyDown、keyPress、keyUp”
    document.onkeyup = function(event){
        event = event || window.event;
        //event对象的keyCode属性用于得到键盘对应键的键码值    
        if(event.keyCode == 13){//回车键码值为13
            if(flag==0){//flag用来记录回车键状态,值为0则表示第一次回车
                playFun();
                flag = 1;
            }else{
                stopFun();
                flag = 0;//恢复flag为0表示这是第一次敲回车
            }
        }

    }

}

//开始抽奖
function playFun(){
    var title = document.getElementById("title"),
        play = document.getElementById("play");
    //每次加载此方法时要清除定时器,避免二次点击导致定时器速度累加
    clearInterval(timer);
    //定时器
    timer = setInterval(function(){
        //每隔50毫秒生成随机数,随机数范围在0到data数组的长度内
        var random = Math.floor(Math.random()*data.length);//floor向下取整
        //console.log(random);
        //根据随机数找到对应的数组项
        title.innerHTML = data[random];
    },50);//每隔50毫秒调用函数
    //点击开始后改变按钮背景颜色
    play.style.background = "#999"; 

}
//停止抽奖
function stopFun(){
    //清除定时器便实现停止开始方法
    clearInterval(timer);
    var play = document.getElementById("play");
    play.style.background = "#036";
}
打开App,阅读手记
38人推荐
发表评论
随时随地看视频慕课网APP

热门评论

好像有个jQuery插件叫做hotkey

网上抽奖从来没中过!!!!

查看全部评论