add autoplay for video in slick carousel

孤人 提交于 2019-12-22 02:38:10

问题


I use slick carousel http://kenwheeler.github.io/slick/ on my page and now I need to add video with autoplay in it.
I use this code
HTML

<div class="main-slider" id="main-slider">
            <div>
                <div class="video-wrapper">
                    <video autoplay loop class="pageBackground-video">
                        <source src="/Content/video/332145276.mp4" type="video/mp4">
                    </video>
                </div>
            </div>
            <div>
                <div class="video-wrapper">
                    <video autoplay loop class="pageBackground-video">
                        <source src="/Content/video/332145276.mp4" type="video/mp4">
                    </video>
                </div>
            </div>          
        </div>

and script

$('#main-slider').slick({
      slidesToShow: 1,
      slidesToScroll: 1,
      autoplay: true,
      autoplaySpeed: 30000,
      dots: true,
      infinite: true,
      adaptiveHeight: true,
      arrows: false
  });

but autoplay doesn't work. Is there any way to make autoplay work?

upd I tried to use

$('#main-slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
  var video = currentSlide.children('video').get(0).play();
});

but I get an error Uncaught TypeError: currentSlide.children is not a function because currentSlide it's just a number (0,1,etc). How to get current element?

upd2 I used this code and it works

$('#main-slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
    $('#main-slider .slick-slide').find('video').get(0).pause();
    var video = $('#main-slider .slick-active').find('video').get(0).play();
});

but now autoplay work for all video perfectly but only after first slick changes. How to make it work for the first video after page only loaded.

upd3 I used this code

 var video = $('#main-slider .slick-active').find('video').get(0).play();

  $('#main-slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
    $('#main-slider .slick-slide').find('video').get(0).pause();
    var video = $('#main-slider .slick-active').find('video').get(0).play();
});

and now all work as I want but I'm afraid my code is ugly (


回答1:


this line of code

$('#main-slider .slick-slide').find('video').get(0).pause();

inside afterChange call back function will pause all the video's present in the slide container irrespective of the video playing or not.

If there are 100 slides, it pauses all 100 videos though they are not playing. Its better you find the previous slide and pause only the video in that slide




回答2:


You Can Just get the id from the video tag and

$("#videotagId").pause();


来源:https://stackoverflow.com/questions/29901228/add-autoplay-for-video-in-slick-carousel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!