foreverwaiting
万人非你X

看书看到的一个jQuery小例子,分享给大家。(jquery引入可以选择下载引入或者在jQuery官网找CDN)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>单机游戏</title>
</head>
<body>
    <div id="container"></div>
    <script src="js/jquery.min.js"></script>
    <script>
        var width=$(window).width(),height=$(window).height(),//首先使用jq获取窗口尺寸
                countdown=20, countup=0;//定义两个变量分别存放剩下要显示的方块数和用户已单击的方块数
        var nextElement=function(){//定义nextElement函数,每调用一次,就添加一个方块到页面中
            if(countdown==0){//剩下要点击的方块数为0时游戏结束
                gameOver();
                return;
            }//未结束时,添加创建一个50*50的方块生成随机的xy位置并且样式化
            var x=Math.random ()*(width-50),y=Math.random ()*(height-50);
            $("<div>").css({
                position:'absolute',
                left:x,top:y,
                width:50,height:50,
                backgroundColor:'red'
            }).appendTo("#container");
            countdown--;
         };
        var gameOver=function(){//定义gameOver函数
            clearInterval (timer);//首先清除间隔定时器,然后弹出一个提醒消息输赢
            if(countup>15){
                alert("You won!");
            }else{
                alert("You lost!");
            }
        };
        var timer=setInterval (nextElement,500);//指向setInterval的调用,每500毫秒创建一个新方块
        $("#container").on('mousedown','div',function(e){//$(selector).on调用,游戏捕获#container元素内部的所有<div>的所有mousedown事件
            countup++;
            $(this).fadeOut();
        });
    </script>
</body>
</html>

 

posted on 2018-05-13 19:31  foreverwaiting  阅读(195)  评论(0编辑  收藏  举报