随机点名器训练,配套的还有网页轮播图训练。
做出来的效果:
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>随机点名</title>
<style>
/* 页面css样式设置 */
.parent{
height: 400px;
width: 800px;
background-color: #f5541b;
border-radius: 10px;/* 设置元素的圆角 */
margin: 10px auto;/*上下边框设置10px,左右设置为auto是为适应浏览器尺寸变化时可随着变换*/
position: relative;/*把psition设置为relative,使得它的子块以它为标准进行边框设置*/
}
.box{
width: 600px;
height: 100px;
border-radius: 10px;
background-color: #bdb9a6;
position: absolute;/*以父块为基础作边框设置*/
margin-top: 100px;
margin-left: 100px;/* (800-300)/2=250 */
font-weight: bold;/*字体加粗*/
font-size: 70px;
text-align: center;/*文本居中*/
}
.button{
width: 100px;
border-radius: 5px;
background-color: green;
position: absolute;/*以父块为基础作边框设置*/
margin-top: 250px;
margin-left: 350px;
cursor: pointer;/*设置鼠标样式*/
}
</style>
</head>
<body>
<h1 align="center">随机点名训练</h1>
<div class="parent">
<div class="box">随机点名器</div>
<button class="button" onclick="fun()">开始</button>
</div>
</body>
<script type="text/javascript">
//数据准备,使用String的数据格式获取名字数组
var nameList = new String("张三,李四,王二,麻子,小明,建国,益达,狗蛋");
var nameArr = nameList.split(',');
var mytime = null;
function fun(){
//获取对应的元素,window可有可无,若不写,系统window默认存在
var button = window.document.getElementsByClassName('button')[0];
if(mytime == null){//没有开始执行随机点名程序
button.style.backgroundColor = "red";
button.innerHTML = '停止';
show();//调用show()方法
}else{//说明直在执行show()
button.style.backgroundColor = 'green';
button.innerHTML = '开始';
//重置mytime
clearTimeout(mytime);
mytime = null;
}
}
//show()方法,不断切换class==box的元素的名字
function show(){
//获取class==box的对象
var box = window.document.getElementsByClassName('box')[0];
//获取随机整数,范围在0-nameLis.length之间
var num = parseInt((Math.random()*10000) % nameArr.length);
//设置box对应元素的值
box.innerHTML = nameArr[num];
//递归调用show()实现不断切换名字
mytime = setTimeout("show()",10);
}
</script>
</html>
刚刚学习,掌握得不扎实,许多属性都是靠查手册才知道用法。