2016-04-30 15 views
2

Ich bin ziemlich neu zu jquery, also habe ich diesen Code aus einer anderen stackoverflow Frage gehängt, aber ich weiß nicht, wie man es anpasst.Autoplay Video auf Bildlauf aber nur einmal

Ich habe ein Video, das automatisch startet, wenn es in das Fenster scrollt. Wenn das Video jedoch pausiert ist und der Benutzer nur ein Pixel scrollt, beginnt das Video erneut. Ich möchte, dass das Video angehalten wird, wenn es sich noch im Fenster befindet, während der Benutzer scrollt.

Im Idealfall würde das Autoplay erneut ausgeführt werden, wenn das Video vollständig außer Sichtweite und dann wieder verschwunden wäre. Es funktioniert auch, wenn diese Autoplay-Funktion nur einmal ausgeführt wird und der Benutzer das Video erneut abspielen kann, wenn es gewünscht wird.

$(document).ready(function() { 
    // Get media - with autoplay disabled (audio or video) 
    var media = $('.autoplay').not("[autoplay='autoplay']"); 
    var tolerancePixel = 40; 

    function checkMedia() { 
     // Get current browser top and bottom 
     var scrollTop = $(window).scrollTop() + tolerancePixel; 
     var scrollBottom = $(window).scrollTop() + $(window).height() - tolerancePixel; 

     media.each(function(index, el) { 
      var yTopMedia = $(this).offset().top; 
      var yBottomMedia = $(this).height() + yTopMedia; 

      if (scrollTop < yBottomMedia && scrollBottom > yTopMedia) 
       $(this).get(0).play(); 
      else 
       $(this).get(0).pause(); 
     }); 
    } 

    $(document).on('scroll', checkMedia); 
}); 

Antwort

0

markieren gerade das Element als gespielt

if(scrollTop < yBottomMedia && scrollBottom > yTopMedia){ 
       if (!$(el).attr('data-played')){ 
       $(el).attr('data-played',1); 
       $(this).get(0).play(); 
       } 
      } else { 
       $(this).get(0).pause(); 
      } 
Verwandte Themen