Play HTML5 Video when scrolled to

前端 未结 4 2231
暖寄归人
暖寄归人 2020-12-02 17:14

Is there anyway to autoplay a HTML5 video only when the user has the video (or a certain percentage of the video) in the browser viewport?

4条回答
  •  独厮守ぢ
    2020-12-02 17:48

    In brief

    Let's say our browser window W currently scrolled to y-position scrollTop and scrollBottom

    Our video will NOT be played when its position is at V1 or V2 as below snapshot.

    Code details

            $(document).ready(function() {
                // Get media - with autoplay disabled (audio or video)
                var media = $('video').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){ //view explaination in `In brief` section above
                            $(this).get(0).play();
                        } else {
                            $(this).get(0).pause();
                        }
                    });
    
                    //}
                }
                $(document).on('scroll', checkMedia);
            });
    

提交回复
热议问题