在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
为了加强对JavaScript原生代码的编写能力,以及巩固setTimeout()的使用方法,制作了一个倒计时的demo,倒计时在现在的网站中算是一个常见的小功能,如果大家喜欢的话可以留下,就当作一个日常实用的小脚本。 实现思路 1、先获取小时值 将小时值减1开始进行倒计时 分钟59 秒数59 实现代码 html <p>倒计时:</p> <span id="hour">5</span> <span>:</span> <span id="minuteTen">0</span> <span id="minuteBit">0</span> <span>:</span> <span id="secondTen">0</span> <span id="secondBit">0</span> css span{ display: inline-block; width: 20px; height: 20px; background-color: #000000; color: #ffffff; text-align: center; } JavaScript function time(){ /*小时*/ var hourTxt = document.getElementById("hour"); var hour = parseInt(document.getElementById("hour").innerHTML); /*分钟*/ var minuteTenTxt = document.getElementById("minuteTen"); var minuteBitTxt = document.getElementById("minuteBit"); var minuteTen = parseInt(document.getElementById("minuteTen").innerHTML); var minuteBit = parseInt(document.getElementById("minuteBit").innerHTML); /*秒*/ var secondTenTxt = document.getElementById("secondTen"); var secondBitTxt = document.getElementById("secondBit"); var secondTen = parseInt(document.getElementById("secondTen").innerHTML); var secondBit = parseInt(document.getElementById("secondBit").innerHTML); function start(){ hour--; hourTxt.innerHTML = hour; minuteTen = 5; minuteTenTxt.innerHTML = minuteTen; minuteBit = 9; minuteBitTxt.innerHTML = minuteBit; secondTen = 5; secondTenTxt.innerHTML = secondTen; secondBit = 9; secondBitTxt.innerHTML = secondBit; /*secondBit开始自减*/ function second(){ secondBit--; secondBitTxt.innerHTML = secondBit; /*十秒过后*/ if(secondBit < 0){ secondTen--; secondTenTxt.innerHTML = secondTen; secondBit = 9; secondBitTxt.innerHTML = secondBit; /*继续倒计时*/ setTimeout(second,1000); /*一分钟过后*/ if(secondTen < 0){ minuteBit--; minuteBitTxt.innerHTML = minuteBit; secondTen = 5; secondTenTxt.innerHTML = secondTen; secondBit = 9; secondBitTxt.innerHTML = secondBit; /*十分钟过后*/ if(minuteBit < 0){ minuteTen--; minuteTenTxt.innerHTML = minuteTen; minuteBit = 9; minuteBitTxt.innerHTML = minuteBit; } /*一个小时过后*/ if(minuteTen < 0){ hour--; hourTxt.innerHTML = hour; minuteTen = 5; minuteTenTxt.innerHTML = minuteTen; minuteBit = 9; minuteBitTxt.innerHTML = minuteBit; secondTen = 5; secondTenTxt.innerHTML = secondTen; secondBit = 9; secondBitTxt.innerHTML = secondBit; } /*倒计时结束*/ if(hour < 0 ){ hour = 0; hourTxt.innerHTML = hour; minuteTen = 0; minuteTenTxt.innerHTML = minuteTen; minuteBit = 0; minuteBitTxt.innerHTML = minuteBit; secondTen = 0; secondTenTxt.innerHTML = secondTen; secondBit = 0; secondBitTxt.innerHTML = secondBit; clearTimeout(second); clearTimeout(start); } } }else{ setTimeout(second,1000); } } setTimeout(second,1000); } setTimeout(start,1000); } 执行页面 结束页面 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持极客世界。 |
请发表评论