前言
在HTML5中,新加入了一个localStorage特性,这个特性主要是用来作为本地存储来使用的,解决了cookie存储空间不足的问题(cookie中每条cookie的存储空间为4k),localStorage中一般浏览器支持的是5M大小,这个在不同的浏览器中localStorage会有所不同。
本文主要介绍了关于jQuery+localStorage实现简易计时器的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
原型

需求
1.关闭浏览器时时间继续运行
2.刷新时保持当前状态
3.结束时间保存在客户端
示例代码
<div class="wrapper">
<div class="app">
<div class="container stopwatch">
<div class="clock inactive z-depth-1">
<span>0:00:00</span>
<!-- <div class="overlay waves-effect"></div>-->
</div>
<form>
<a id="stopwatch-btn-start" class="waves-effect waves-teal btn-flat">开始</a> </form>
</div>
</div>
</div>
<script>
// Stopwatch
var stopwatchInterval = 0; // The interval for our loop.循环的间隔。
var stopwatchClock = $(".container.stopwatch").find(".clock"),
stopwatchDigits = stopwatchClock.find('span');
// 检查前一个会话是否在秒表运行时结束。
// 如果是的话,按时间重新开始。
//即 关闭浏览器,点击开始,在后台保持计时的状态
if(Number(localStorage.stopwatchBeginingTimestamp) && Number(localStorage.stopwatchRunningTime)){
var runningTime = Number(localStorage.stopwatchRunningTime) + new Date().getTime() - Number(localStorage.stopwatchBeginingTimestamp);
localStorage.stopwatchRunningTime = runningTime;
startStopwatch();
}
//如果前一个会话有运行时间,就把它写在时钟上。
// 如果没有初始化为0。
//即结束时不可刷新
if(localStorage.stopwatchRunningTime){ stopwatchDigits.text(returnFormattedToMilliseconds(Number(localStorage.stopwatchRunningTime)));
}
else{
localStorage.stopwatchRunningTime = 0;
}
/* 实现开始结束 */
$("#stopwatch-btn-start").toggle(function() {
$(this).text ('开始').css("background", "#3bb4f2");
if(stopwatchClock.hasClass('inactive')){
startStopwatch()
}
}, function() {
$(this).text ('结束').css("background", "red");
pauseStopwatch();
})
// Pressing the clock will pause/unpause the stopwatch.










