Maison  >  Article  >  interface Web  >  jQuery+localStorage implémente une minuterie

jQuery+localStorage implémente une minuterie

php中世界最好的语言
php中世界最好的语言original
2018-03-15 14:12:291946parcourir

Cette fois, je vais vous apporter jQuery+localStorage pour implémenter un timer. Quelles sont les précautions pour jQuery+localStorage pour implémenter un timer. Voici un cas pratique, jetons un coup d'œil.

Avant-propos

En HTML5, une nouvelle fonctionnalité localStorage a été ajoutée. Cette fonctionnalité est principalement utilisée comme stockage local pour résoudre le problème. d'espace de stockage insuffisant du cookie (l'espace de stockage de chaque cookie dans le cookie est de 4k). Généralement, les navigateurs prennent en charge une taille de 5M dans localStorage. Ce localStorage sera différent selon les navigateurs.

Cet article présente principalement le contenu pertinent sur jQuery+localStorage pour implémenter une minuterie simple. Il est partagé pour la référence et l'apprentissage de chacun. Je ne dirai pas grand-chose ci-dessous, jetons un œil à l'introduction détaillée.

Prototype

Exigences

1. L'heure continue de s'écouler lorsque le navigateur est fermé

2. Conserver l'état actuel lors de l'actualisation

3. L'heure de fin est enregistrée sur le client

Exemple de code

 <p class="wrapper">
  <p class="app">
  <p class="container stopwatch">   
   <p class="clock inactive z-depth-1">
   <span>0:00:00</span>
   <!-- <p class="overlay waves-effect"></p>-->
   </p>   
   <form>
   <a id="stopwatch-btn-start" class="waves-effect waves-teal btn-flat">开始</a>
   </form> 
  </p>
  </p>
 </p>
<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.
//按下暂停/恢复的时钟秒表
/*stopwatchClock.on('click',function(){
 if(stopwatchClock.hasClass('inactive')){
 startStopwatch()
 }
 else{
 pauseStopwatch();
 }
});*/
/*开始计时*/
function startStopwatch(){
 // 防止多个间隔同时进行。 
 clearInterval(stopwatchInterval);
 var startTimestamp = new Date().getTime(),
 runningTime = 0;
 localStorage.stopwatchBeginingTimestamp = startTimestamp;
 // 应用程序还记得上一次会话运行了多长时间。 
 if(Number(localStorage.stopwatchRunningTime)){
 runningTime = Number(localStorage.stopwatchRunningTime);
 }
 else{
 localStorage.stopwatchRunningTime = 1;
 }
 // 每隔100ms重新计算运行时间,计算公式是 
 // 当你上次启动时钟+上次运行时间 
 stopwatchInterval = setInterval(function () {
 var stopwatchTime = (new Date().getTime() - startTimestamp + runningTime);
 stopwatchDigits.text(returnFormattedToMilliseconds(stopwatchTime));
 }, 100);
 stopwatchClock.removeClass('inactive');
}
/*停止计时*/
function pauseStopwatch(){
 // 停止计时 
 clearInterval(stopwatchInterval);
 if(Number(localStorage.stopwatchBeginingTimestamp)){
 // 计算运行时间。 
 // 新的运行时间=上次运行时间+现在-最后一次启动 
 var runningTime = Number(localStorage.stopwatchRunningTime) + new Date().getTime() - Number(localStorage.stopwatchBeginingTimestamp);
 localStorage.stopwatchBeginingTimestamp = 0;
 localStorage.stopwatchRunningTime = runningTime;
 stopwatchClock.addClass('inactive');
 }
}
// 重置.
/*function resetStopwatch(){
 clearInterval(stopwatchInterval);
 stopwatchDigits.text(returnFormattedToMilliseconds(0));
 localStorage.stopwatchBeginingTimestamp = 0;
 localStorage.stopwatchRunningTime = 0;
 stopwatchClock.addClass('inactive');
}
*/
function returnFormattedToMilliseconds(time){
 var 
 seconds = Math.floor((time/1000) % 60),
 minutes = Math.floor((time/(1000*60)) % 60),
 hours = Math.floor((time/(1000*60*60)) % 24);
 seconds = seconds < 10 ? &#39;0&#39; + seconds : seconds;
 minutes = minutes < 10 ? &#39;0&#39; + minutes : minutes;
 return hours + ":" + minutes + ":" + seconds;
}
</script>

Je crois que vous maîtrisez la méthode après avoir lu le cas dans cet article. Pour un contenu plus passionnant, veuillez prêter attention aux autres articles connexes sur le site Web chinois de php !

Lecture recommandée :

jQuery ajoute de nouveaux éléments aux listes dynamiques

Service client en ligne de tiroir jQuery pratique

Comment utiliser jQuery pour sélectionner et utiliser une table

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn