HTML代码
<style>
.container {
width: 300px;
text-align: center;
margin: 0 auto;
}
#showNum {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height: 300px;
font-size: 30px;
font-weight: 900;
border-radius: 50%;
box-shadow: 0 0 4px rgba(0, 0, 0, .45);
}
#btn {
width: 100px;
height: 40px;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<div id="showNum">web2206A02</div>
<button id="btn">开始</button>
</div>
</body>
JavaScript代码部分
方法一
<script>
var oDiv = document.getElementById("showNum");
var oBtn = document.getElementById("btn");
var timer = null, count = 0, flag = false;
oBtn.onclick = function () {
count++;
if (count % 2 === 1) {//点击第奇数次
this.innerText = "停止";
timer = setInterval(randNum, 100);//开始计时器
} else {//点击第偶数次
this.innerText = "开始";
clearInterval(timer);//停止计时器
}
}
function randNum() {
var num = Math.floor(Math.random() * 35 + 1) //[1,35]
if (num < 10) {
num = "0" + num; // 使一位数变成两位数
}
oDiv.innerHTML = "web2206A" + num;
}
</script>
方法二
<script>
var oDiv = document.getElementById("showNum");
var oBtn = document.getElementById("btn");
var timer = null, count = 0, flag = false;
oBtn.onclick = function () {
if (!flag) {
this.innerText = "停止";
timer = setInterval(randNum, 100);//开始计时器
flag = true;
} else {
this.innerText = "开始";
clearInterval(timer);//停止计时器
flag = false;
}
}
function randNum() {
var num = Math.floor(Math.random() * 35 + 1) //[1,35]
if (num < 10) {
num = "0" + num;
}
oDiv.innerHTML = "web2206A" + num;
}
</script>
运行结果:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/46302.html