A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© PHP吴嘉伟 中级黑马   /  2018-1-21 09:46  /  1366 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

JavaScript的抽奖
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4.   <meta charset="utf-8">
  5.   <title>抽奖活动</title>
  6.   <style>
  7. *{
  8. margin:0;padding:0;
  9. }
  10. #title{
  11. color:red;text-align:center;margin:0 auto;width:240px;height:70px;padding-top:10px;background:opacity(0);
  12. }
  13. .btns{
  14. width:190px;height:30px;margin:0px auto;
  15. }

  16. .btns span{
  17. display:block;float:left;width:80px;height:28px;text-align:center;background:#036;color:#fff;cursor:pointer;border:1px solid #eee;border-radius:8px;font-family:"微软雅黑";font-size:14px;line-height:28px;margin-right:10px;
  18. }
  19. #txt{
  20. font-size:14px;color:#ccc999;text-align:center;margin:0 auto;width:190px;height:50px;padding-top:10px;
  21. }
  22.   </style>
  23.   <script>
  24. var mytype=["iPhone6s","iPad Air2","DELL外星人","键鼠套装","1000元超市购物卡","200元话费充值卡","谢谢参与","品牌耳机","港澳台7日游","50元优惠券"],//定义奖品池
  25.    timer=null,
  26.    count=0;
  27. //加载时触发
  28. window.onload=function(){
  29. var start = document.getElementById("start");
  30. var stop = document.getElementById("stop");

  31. start.onclick=startFun;//这个函数后面加括号,就直接调用了该函数,所以不要加
  32. stop.onclick=stopFun;

  33. //绑定键盘事件
  34. document.onkeyup=function(e){
  35.    e = e || window.event;
  36.   if(e.keyCode==13){
  37.     if(count==0){
  38.     startFun();
  39.     count=1;
  40.     }
  41.   else{
  42.     stopFun();
  43.     count=0;
  44.     }
  45.   }
  46. }
  47. }

  48. //点击开始,标题栏开始轮动
  49. function startFun(){
  50.   clearInterval(timer);//开始时,清除计时器,避免二次触发
  51.   var title = document.getElementById("title");
  52.   var start = document.getElementById("start");

  53.   timer = setInterval(function(){
  54.     var num= Math.floor(Math.random()*mytype.length);
  55.     title.innerHTML=mytype[num];
  56.   },50);
  57.   start.style.background="#ccc";

  58. }
  59. //点击停止,标题栏停止轮动并输出轮动结果
  60. function stopFun(){
  61.   var start = document.getElementById("start"),
  62.     txt = document.getElementById("txt"),
  63.     title = document.getElementById("title");
  64.   clearInterval(timer);//清除计时器,停止计时器
  65.   start.style.background="#036";
  66. }


  67.   </script>
  68. <body>
  69. <div>
  70. <h2 id="title">开始抽奖!</h2>
  71. </div>
  72. <div class="btns">
  73. <span id="start">开始</span>
  74. <span id="stop">停止</span>
  75. </div>
  76. </body>
  77. </html>
复制代码


总体比较简单,但是关键点在于两个 1.定时器的运用 2.js的数组下标 如何取

2 个回复

倒序浏览
传智第一大帅逼!

点评

传智第一大帅逼!  发表于 2018-1-21 21:01
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马