學習js一個月利用已學的知識寫了一個簡單的抽獎
先看效果圖,比較簡單

html代碼
<div class="big">
<div class="small" id="act">越南美女</div>
<div class="small">超詳細前端課</div>
<div class="small">平板</div>
<div class="small">500元紅包</div>
<div id="cj">點擊抽獎</div>
<div class="small">66紅包</div>
<div class="small">精美桃子一個</div>
<div class="small">鑰匙扣</div>
<div class="small">謝謝參與</div>
</div>
css代碼
* {
margin: 0;
padding: 0;
list-style: none;
}
.big {
width: 318px;
height: 318px;
margin: 100px auto;
}
.big>div {
width: 100px;
height: 100px;
background: #48D1CC;
float: left;
line-height: 100px;
text-align: center;
border: solid;
}
.big>div:nth-of-type(5) {
background: #008B8B;
cursor: pointer;
}
#act {
background: #20B2AA;
}
js代碼
給抽獎的盒子系結點擊事件
this.oCj.addEventListener('click', this.outFn.bind(this))
因為要用到定時器所以封裝一個清除定時器的函式
stop() {
clearInterval(this.outime);
}
然后定時器,我用的倒計時來停止
this.outime = setInterval(this.clickFn.bind(this), 100);
setTimeout(this.stop.bind(this), this.time);
主要代碼段,讓他一直走,設定樣式,前面的取消樣式
this.num += 1;
if (this.num > this.arrDiv.length - 1) {this.num = 0;}
for (let i = 0; i < this.arrDiv.length; i++) {this.arrDiv[i].id = '';}
this.arrDiv[this.num].id = "act";
js所有代碼,歡迎補充修改
class Draw {
constructor() {
this.arrDiv = this.$$('small')
//console.log(this.arrDiv);
this.oCj = this.$('#cj');
this.num = 0;
this.oCj.addEventListener('click', this.outFn.bind(this))
}
outFn() {
this.time = Math.round(Math.random() * 4000 + 5000);
this.outime = setInterval(this.clickFn.bind(this), 100);
this.stop.bind(this);
setTimeout(this.stop.bind(this), this.time);
}
clickFn() {
this.num += 1;
if (this.num > this.arrDiv.length - 1) {
this.num = 0;
}
for (let i = 0; i < this.arrDiv.length; i++) {
this.arrDiv[i].id = '';
}
this.arrDiv[this.num].id = "act";
}
stop() {
clearInterval(this.outime);
}
$(ele) {
return document.querySelector(ele)
}
$$(ele) {
return document.getElementsByClassName(ele)
}
}
new Draw;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/298968.html
標籤:其他
上一篇:手把手教你寫自動化路由
