2017-12-02 128 views
0

我有以下代碼,通過具有data-slides屬性的頁面上的每個div指定要顯示的圖像。它通過淡入和淡出他們的動畫在一個循環中不同的圖像:OnClick的暫停動畫

(function($) { 
'use strict'; 
$('[data-slides]').each(function(){ 
     var $slides = $(this); 
     var images = $slides.data('slides'); 
     var count = images.length; 
     var number = 0; 
     var slideshow = function() { 
      $slides 
       .css('background-image', 'url("' + images[number%count] + '")') 
       .show(0, function() { 
        setTimeout(slideshow, 3500); 
       }); 
       number++; 
     }; 

     slideshow(); 
    }); 
}(jQuery)); 

我想要做的是有再次啓動的幻燈片動畫按鈕暫停正在製作動畫的特定元素,然後另一個按鈕。我怎樣才能做到這一點?謝謝!

編輯

使用從Flash雷霆的建議,我已經有獨立的定時器,可暫停更新它:

function Timer(callback, delay) { 
    var timerId, start, remaining = delay; 

    this.pause = function() { 
     window.clearTimeout(timerId); 
     remaining -= new Date() - start; 
    }; 

    this.resume = function() { 
     start = new Date(); 
     window.clearTimeout(timerId); 
     timerId = window.setTimeout(callback, remaining); 
    }; 

    this.resume(); 
} 

function runSlideshow(div){ 
    var $slides = div; 
    var images = $slides.data('slides'); 
    var count = images.length; 
    var number = 0; 
    this.slideshow = function() { 
     $slides 
      .css('background-image', 'url("' + images[number%count] + '")') 
      .show(0, function() { 
       timer.resume(); 
      }); 
      number++; 
    }; 
    var timer = new Timer(this.slideshow, 3500); 

    this.slideshow(); 
} 

(function($) { 
    'use strict'; 
    $('[data-slides]').each(function() { 
      var run = new runSlideshow($(this)); 
      run.slideshow(); 
    }); 
}(jQuery)); 

這工作,但我需要能夠從$('[data-slides]')的任何一個訪問定時器以便能夠暫停它。我怎麼能夠?

+0

你可以添加你的HTML,它可能會更容易添加一個片段與運行的例子與你想要的修復 –

回答

0
function Timer(callback, delay) { 
    var timerId, start, remaining = delay; 

    this.pause = function() { 
     window.clearTimeout(timerId); 
     remaining -= new Date() - start; 
    }; 

    this.resume = function() { 
     start = new Date(); 
     window.clearTimeout(timerId); 
     timerId = window.setTimeout(callback, remaining); 
    }; 

    this.resume(); 
} 

var timer = new Timer(function() { 
    alert("Done!"); 
}, 1000); 

timer.pause(); 
// Do some stuff... 
timer.resume(); 

致謝Tim Down

+0

你認爲你可以定製這個我的代碼?我不是本地的JS開發人員,所以我不太清楚這是如何涉及的。 – Tometoyou

+0

將此函數添加到您的代碼中,使用具有相同參數而不是'setTimeout'的'timer',然後您可以隨時調用'timer.pause()'和'timer.resume()'。例如在'onclick'事件中。 –

+0

好酷我已經設法做到這一點。但是,如何從單獨的onclick事件訪問計時器?因爲我對元素運行了一個foreach循環,所以很難訪問它。我已更新我的代碼... – Tometoyou