本文实例为大家分享了JS倒计时效果的具体代码,供大家参考,具体内容如下
Index.html
倒计时function toTwo(n)
{
if(n>9)
{
return ''+n;
}
else
{
return '0'+n;
}
}
window.οnlοad=function(){
var oBox=document.getElementById('box');
var aImg=oBox.getElementsByTagName('img');
function time()
{
var enddate=new Date('2016/12/25 00:00:00');
var mydate=new Date();
var str='';
var t=enddate.getTime()-mydate.getTime();
str=toTwo(Math.floor(t/1000/60/60/24))+toTwo(Math.floor(t/1000/60/60%24))+toTwo(Math.floor(t/1000/60%60))+toTwo(Math.floor(t/1000%60));
for(var i=0;i
{
aImg[i].src='images/'+str[i]+'.png';
}
}
time();
setInterval(time,1000);
};
#box { width:1000px;
height:200px;
font-size:14px;
line-height:100px;
margin:auto;
}
#box img{ width:30px;
height:60px;
}
天:
时:
分:
秒
运行结果如图:
上面的图片需要
方法二、JavaScript倒计时栏的实现
这边小编也是刚刚过完双11呀(快递还没有到很绝望),剁完手来写上这新学的知识。双十一很多电商网站随处可见倒计时的框图那他们到底是怎样实现的时刻计时。
主要用法在于对js中Data对象的方法,话不多说直接撸上代码,主要难点在于对每一项时间的获取
#countdown{
margin: 200px auto;
font-size: 20px;
text-align: center;
color: red;
}
window.οnlοad=function(){
var enddata=new Date("2018/12/12 00:00:00"); //这边是自定义的截止时间
var div=document.getElementById("countdown");
function hold(){
var nowtime=new Date(); //每一次执行获取当前时间
var second=parseInt((enddata.getTime()-nowtime.getTime())/1000);
var minute=parseInt(second/60%60);
var hour=parseInt(second/3600%24);
var day=parseInt(second/3600/24);
second=second%60;
second<10 ? second="0"+second : second; //此下四行确保格式每一位数都是标准的两位
minute<10 ? minute="0"+minute : minute;
hour<10 ? hour="0"+hour : hour;
day<10 ? day="0"+day : day;
div.innerHTML="距离双十二开抢还有"+day+"天"+hour+"小时"+minute+"分"+second+"秒";
}
setInterval(hold,1000); //每一秒执行一次,这边第二个参数为毫秒单位
}
效果图如下(动态变化):
主要在于setInterval(); 方法,其余部分小编已经写上了备注,当然这边只是简单的写了一下样式。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。