需求:鼠标点击开始或者键盘回车事件发生,文本开始改变。点击结束或键盘回车事件再次发生时结束。
样式图如下:
html代码实现:页面中只有一个内容区块,其中包含一个文本和两个按钮。
(注意:无论案例大小,始终试着将结构和样式相分离。)
<div class="content">
<p class="text" id="text"> 笔记本电脑 </p>
<span class="start btn" id="start">开 始</span>
<span class="stop btn" id="stop">结 束</span>
</div>
css代码实现:
body,*{
margin: 0;
padding: 0;
}
.content{
width: 200px;
height: 80px;
margin: 0 auto;
margin-top: 40px;
}
.text{
height: 40px;
color: #f00;
font-size: 28px;
font-weight: bold;
text-align: center;
}
.btn{
display: inline-block;
width: 80px;
height: 30px;
line-height: 30px;
border-radius: 6px;
font-size: 16px;
color: white;
text-align: center;
background-color: cornflowerblue;
margin-top: 10px;
margin-left: 10px;
cursor: pointer;
}
js代码实现:
let arr = ['笔记本电脑','苹果电脑','台式电脑','手机','苹果手机','老年机'],
timer = null,
flage = 0;
window.onload = function(){
let text = document.getElementById("text"),
start = document.getElementById("start"),
stop = document.getElementById("stop");
//鼠标点击事件
start.onclick = goStart;
stop.onclick = toEnd;
//键盘回车事件
document.onkeyup = function(event){
//浏览器适配性问题
event = event || window.event;
if(event.keyCode == 13){
flage == 0?goStart():toEnd();
}
}
}
function goStart(){
let start = document.getElementById("start"),
text = document.getElementById("text");
start.style.background = "#ccc";
flage = 1;
//每次开始新的定时器时清除上一个定时器
clearInterval(timer);
timer = setInterval(function(){
let index = parseInt(Math.random()*(arr.length));
text.innerHTML = arr[index];
},50)
}
function toEnd(){
flage = 0;
let start = document.getElementById("start");
clearInterval(timer);
start.style.background = "cornflowerblue";
}
总结:写html代码的时候,尽量不要用div去控制位置,需要在html里面完成的是结构和语义化,即页面有什么内容就写什么。写js的时候尽量精简代码,本次也是我第一次自觉的开始写三元式。本博文是学习慕课网课程后的一个demo。
注意:博文只是为了记录本人的学习。