在滑块中播放视频,然后在最后交换图像

时间:2015-04-20 13:26:42

标签: javascript jquery html video

所以我目前在HeroCarousel slider内播放视频。滑块前有一个图像,滑块后有另一个图像。

我的代码:

<div data-time="8000"  data-prev-src="/media/splash/slider-left.png" data-next-src="/media/splash/slider-right.png">
  <a href="/island-careers/retail.html">
    <img src="/media/island/splash/now-hiring-splash.jpg" />
  </a>
</div>
<div data-time="9000" data-video="true" data-prev-src="/media/splash/slider-left-black.png" data-next-src="/media/splash/slider-right-black.png" id="video">
  <a href="/catalog/island-collections/packing-list/">
    <video width="1275" height="557" preload="auto" id="myVideo">
      <source src="/media/island/splash/video-2.mp4" type="video/mp4">
    </video>
    <img src="/media/island/splash/escape-splash.jpg" />
  </a>
</div>
<div data-time="8000"  data-prev-src="/media/splash/slider-left.png" data-next-src="/media/splash/slider-right.png">
  <a href="/catalog/mens-resort-wear/classic-shirts/breaker-striped-red-linen-shirt.html">
    <img src="/media/island/splash/breakers-shirt-splash.jpg" />
  </a>
</div>

所以我的问题是视频在页面加载时播放。当幻灯片进入视图时,视频已经处于完成的帧中。我希望在幻灯片进入视图时播放视频,而不是在页面加载时播放。滑块将类current添加到当前幻灯片,因此我开始编写以下脚本以使其播放:

//playing video
jQuery(document).ready(function() {
  $play = 0;

  if($play > 0) {
    if(jQuery("article#video").hasClass("current")) {
      jQuery("#myVideo").get(0).play();
      $play++;
    }
  }

});

此脚本无法正常运行。

我还想在视频结束后将视频换成在其下方找到的图片(视频应该只播放一次)

1 个答案:

答案 0 :(得分:0)

实现此目标的一种方法是使用标记并收听DOMSubtreeModifiedended事件。

仅在幻灯片可见时启动视频,您可以

var canPlay = false, played = false;
$('.hero-carousel article').bind('DOMSubtreeModified', function(e) {
    if(played){     // flag to make sure it is played only once.
        $('.hero-carousel article').unbind('DOMSubtreeModified');
    }else if($(e.target).hasClass('current')){
        canPlay = true;     // flag to make sure, playing starts only when slide is current.
        var video = $(e.target).find('video')[0];
        if(video){
            video.play();            
        }
    }
});

$('.hero-carousel article video').bind('play', function(){
    if(!canPlay){
        this.pause();
        this.currentTime = 0;
    }else{
        played = true;
    }               
});    

并在视频完成后隐藏视频,您可以执行以下操作:

$('.hero-carousel article video').bind('ended', function(){
    this.style.display = 'none';
});

fiddle demo