本文主要是介绍js实现从0开始计时及显示当前时间,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
需求:
页面点击进来,就从0开始计时,动态显示用户停留在该页面的时间。
思路:
记录用户进入该页面的时间(初始时间);
不断用当前时间-初始时间=在该页面的停留时间;
需要注意的是,应该将js函数Time()放到<body>的onload中,即页面一加载就执行
js函数应该放在<head>标签中
js:
<script type="text/javascript">/** 显示当前时间函数* YQ*/function Time(){var today=new Date(); var h=today.getHours();var m=today.getMinutes();var s=today.getSeconds();duration(h,m,s);// add a zero in front of numbers<10m=checkTime(m);s=checkTime(s);document.getElementById('timeshow').value=h+":"+m+":"+s;t=setTimeout('Time()',500); //暂停0.5后执行Time()函数}/** 个位数时补0*/function checkTime(i) {if (i<10) {i="0" + i}return i}/** 历时:当前时间-开始时间* @author YQ*/function duration(nh,nm,ns){var beginTime = document.getElementById('beginTime').value; //获取计时初始值var beginT = new Array();beginT = beginTime.split(" ");beginT = beginT[1].split(":");var sh = Number(beginT[0]);var sm = Number(beginT[1]);var ss = Number(beginT[2]);//换算历时 h:m:svar allS = (nh*3600+nm*60+ns)-(sh*3600+ sm*60 +ss);var dh = parseInt(allS/3600);var dm = parseInt((allS-dh*3600)/60);var ds = allS - dh*3600 - dm*60;document.getElementById('duration').value = dh+':'+dm+':'+ds;}</script>
html:
<body οnlοad="Time()">
<b>历时:</b><input type="text" id="duration" style="border:0px;background-color:transparent;width:80px;" />
<b>当前时间:</b><input type="text" id="timeshow" style="border:0px;background-color:transparent;width:80px;" />
</body>
这篇关于js实现从0开始计时及显示当前时间的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!