## JavaScript点击事件
JavaScript中的常见的事件有点击事件、焦点事件、加载事件、鼠标键盘事件、选中和改变事件和表单事件。
其中点击事件又分为单击事件和双击事件,我们知道,点击鼠标左键如果手速很快的话肉眼是很难看出来的(听不到鼠标点击左键声音的情况下),这样的话我们就可以来一手黑幕操作!
在学习点击事件前,我们的点名器都是随机抽取同学的,但是在学习了点击事件后,事情就变得有趣起来了。
我们先看代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点名</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
.box {
width: 200px;
height: 200px;
line-height: 200px;
background-color: #ccc;
font-size: 30px;
text-align: center;
margin: 40px auto;
}
.btn_a{
margin: 0px 750px;
width: 50px;
height: 50px;
}
#btn{
width: 50px;
height: 25px;
}
</style>
<body>
<div class="box">此乃点名器</div>
<div class="btn_a">
<input type="button" value="点名" id="btn">
</div>
<script>
var btn = document.getElementById("btn");
var box = document.getElementsByClassName("box")[0];
btn.onclick = function() {
if(this.value==="点名") {
function fn() {
var arr = ["丁一","刘二","赵四","田七","老六","苟八","王五","张三"];
var index = parseInt(Math.random() * arr.length);
box.innerHTML = arr[index];
}
this.value = "停止";
timer=setInterval(fn,25);
}else {
clearInterval(timer);
this.value = "点名";
}
}
btn.ondblclick = function() {
if(this.value==="停止") {
box.innerHTML = "赵四";
clearInterval(timer);
this.value = "点名";
}
}
</script>
</body>
</html>
我们可以通过<style></style>自己设置点名器的样式,然后就是分别设置单击事件和双击事件的方法,当我们单击“点名”按钮时,预存的名字开始转动,当我们单击“停止”按钮时,显示框中就会随机出现一位同学的名字。但如果我们双击“停止”按钮时,显示框中就会出现我们在双击事件方法中指定的同学的名字
btn.ondblclick = function() {
if(this.value==="停止") {
box.innerHTML = "赵四";
clearInterval(timer);
this.value = "点名";
}
}
而我们只需要在这段双击事件方法的代码中在 box.innerHTML= " "; 的双引号中加入我们想要的名字,就可以在点名器启动过后通过双击“停止”按钮一直抽到此位同学啦!