<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box1{
width: 700px;
height: 600px;
background-color: orange;
margin: auto;
position: relative;
}
.box2{
width: 200px;
height: 200px;
background: wheat;
position: absolute;
left: 50px;
top: 150px;
font: 30px arial;
color: red;
line-height: 200px;
text-align: center;
}
.box3{
width: 200px;
height: 200px;
background: wheat;
position: absolute;
left: 450px;
top: 150px;
font: 30px arial;
color: red;
line-height: 200px;
text-align: center;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2" id="sb"></div>
<input type="button" style="margin: 500px 210px;" value="开始" onclick="boxone()" />
<div class="box3" id="sth"></div>
<input type="button" value="结束" onclick="boxtwo()" />
</div>
<script type="text/javascript">
var sname=["小黄","小红","小蓝","小绿","小青","小紫","小橙"];
var sthing=["吃瓜","卖萌","嗑瓜子","搬凳子","看戏","卖汽水"];
var timer;
function boxone(){
clearTimeout(timer);
document.getElementById("sb").innerHTML=
sname[Math.floor(Math.random()*sname.length)];
document.getElementById("sth").innerHTML=
sthing[Math.floor(Math.random()*sthing.length)];
timer=setTimeout(boxone,200);
}
function boxtwo(){
clearTimeout(timer);
}
</script>
</body>
</html>
要求:点击开始后,姓名与事件每200ms变换一次,当点击结束后,停止变换,随机显示一个姓名与事件
————
定义两个数组,一个装姓名,一个装事件,顺便定义一个定时器名
var sname=["小黄","小红","小蓝","小绿","小青","小紫","小橙"];
var sthing=["吃瓜","卖萌","嗑瓜子","搬凳子","看戏","卖汽水"];
var timer;
//document.getElementById("sb").innerHTML 获取到的ID名为sb的元素里面的内容
//Math.floor(Math.random()*sname.length) 随机生成一个0到sname.length(两个边界均不包含)之间的数并向下取整,以此来随机生成一个数组sname的下标。
//此段代码意为在数组sname中随机找一个元素将其赋给ID名为sb的元素。
document.getElementById("sb").innerHTML=
sname[Math.floor(Math.random()*sname.length)];
//事件的处理方法一样
————
利用定时器每200ms调用一次函数,为了使滚动速度不会越来越快,每使用定时器调用一次函数,都需要清除上一个定时器。
function boxone(){
clearTimeout(timer);
document.getElementById("sb").innerHTML=
sname[Math.floor(Math.random()*sname.length)];
document.getElementById("sth").innerHTML=
sthing[Math.floor(Math.random()*sthing.length)];
timer=setTimeout(boxone,200);
}
————
这里结束按钮的方法,清除定时器就行了
function boxtwo(){
clearTimeout(timer);
}