//实现思路:
弄两个函数,一个开始函数,一个停止函数。。
点击开始按钮的时候,开始随机筛选。
点击结束按钮的时候。结束筛选。 清除定时器。
用到的知识点:数组,随机数,setinterval,clearinterval,点击事件函数
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="box">
<p><span id="">黄忠</span></p>
<button onclick="run_star()" id="begin">点击开始</button>
<button onclick="run_stop()" id="stop">点击结束</button>
</div>
<script type="text/javascript">
var span = document.getElementById('box').getElementsByTagName('span')[0]; //获取span节点
var btn_star = document.getElementsByTagName('button')[0]; //获取开始按钮的节点
var btn_stop = document.getElementsByTagName('button')[1]; //获取结束按钮的节点
var time; //先定义个空的定时器变量,等待赋值
function run_star() { //开始按钮 的函数
time = setInterval(function() {
var arr = ['张飞', '关羽', '赵云', '吕布', '刘备', '曹操']; //定义一个容器来存储名字
var arr_index = Math.floor(Math.random() * arr.length); //随机生成一个数组的索引值
var arr_random = arr[arr_index]; //通过索引值随机生成的数组中的某个名字
span.innerHTML = arr_random; //将随机生成的这个名字赋值给span的innerHTML属性。
}, 100)
}
function run_stop() { //结束按钮的函数
clearInterval(time); //清除定时器,即停止通过time启动的这个函数。
}
</script>
<style type="text/css">
div {
position: relative;
margin: 0 auto;
width: 300px;
height: 300px;
background: burlywood;
}
div p {
font-weight: bold;
color: darkgreen;
font-size: 30px;
width: 100%;
position: absolute;
top: 100px;
text-align: center;
}
#begin {
position: absolute;
float: left;
bottom: 0px;
}
#stop {
float: right;
}
</style>
</body>
</html>