js抽奖问题,新人求解

JavaScript06

js抽奖问题,新人求解,第1张

用一个setinterval方法就搞定了

请点击输入图片描述

代码(用了JQuery):

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<script id="script" type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

</head>

<body>

<input id="C" type="" name=""><button id="sta">Start</button>

<input id="E" type="" name=""><button id="sto">Stop</button>

<script type="text/javascript">

var arr = ['A','B','C','D','E']

function getR(){

return Math.floor(Math.random()*arr.length)

}

var t=0

$('#sta').click(function(){

t=window.setInterval(function(){

let tt = arr[getR()]

$('#C').val(tt)

},300)

})

$('#sto').click(function(){

window.clearInterval(t)

$('#E').val($('#C').val())

})

</script>

</body>

</html>

本文实例为大家分享了js抽奖程序的编写代码,以及编写注意事项,感兴趣的小伙伴们可以参考一下

代码:

<!DOCTYPE

html>

<html

lang="en">

<head>

<meta

charset="UTF-8">

<title>简单抽奖(可用键盘)</title>

<style>

*{margin:0padding:0}

.box{width:

400pxheight:

300pxmargin:50px

autobackground:

red}

.title{color:

#ffffont-size:

30pxfont-weight:700pxpadding:

50px

0text-align:

centerheight:40px}

.btm{text-align:

centerpadding:20px

0}

.btm

a{display:

inline-blockwidth:

120pxheight:60pxline-height:

60pxbackground:

#FEF097margin:0

10pxtext-decoration:

none}

</style>

<script>

var

data=['Iphone','Ipad','笔记本','相机','谢谢参与','充值卡','购物券'],

timer=null,//定时器

flag=0//阻止多次回车

window.onload=function(){

var

play=document.getElementById('play'),

stop=document.getElementById('stop')

//

开始抽奖

play.onclick=playFun

stop.onclick=stopFun

//

键盘事件

document.onkeyup=function(event){

event

=

event

||

window.event

//

回车键的code值:13

if(event.keyCode==13){

if(flag==0){

playFun()

flag=1

}else{

stopFun()

flag=0

}

}

}

function

playFun(){

var

title=document.getElementById('title')

var

play=document.getElementById('play')

clearInterval(timer)

timer=setInterval(function(){

var

random=Math.floor(Math.random()*data.length)

title.innerHTML=data[random]

},60)

play.style.background='#999'

}

function

stopFun(){

clearInterval(timer)

var

play=document.getElementById('play')

play.style.background='#FEF097'

}

}

</script>

</head>

<body>

<div

class="box">

<div

class="title"

id="title">淘家趣抽奖</div>

<div

class="btm">

<a

href="javascript:"

id="play">开始</a>

<a

href="javascript:"

id="stop">停止</a>

</div>

</div>

</body>

</html>

注意点:

1.随机数,取数组的其中一个;取0-n之间:Math.random()*(n+1)

2.定时器,开始抽奖时要停止前面的一次抽奖,不然会定时器重叠

3.按键操作,要判断是抽奖进行中,还是未开始,所有设置了变量

flag

想要学习更多关于javascript抽奖功能,请参考此专题:javascript实现抽奖功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

1~36个数取7个不同的,需要用while循环+随机数去取出7个数。

在while循环里面,可以判断取出来的数(用switch),是否是28,18,8. 如果有输出相应的奖项,如果没有,就输出其它的。然后将这7个数,打印出来就好了。

JavaScript(缩写为JS)是一种高级的、多范式、解释型的编程语言,是一门基于原型、函数先行的语言,它支持面向对象编程、命令式编程以及函数式编程。

它提供语法来操控文本、数组、日期以及正则表达式,不支持I/O(比如网络、存储和图形等),但可以由它的宿主环境提供支持。它已经由ECMA(欧洲计算机制造商协会)通过ECMAScript实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器支持。