HTML5 and Javascript to play videos only when visible

前端 未结 11 642
梦如初夏
梦如初夏 2020-12-02 12:25

I am interested in setting up an HTML page with multiple video clips such that each video clip plays only while visible and then pauses when out of view.

I have fo

11条回答
  •  庸人自扰
    2020-12-02 13:22

    None of the above seemed to work for me, but I finally found a way: you'll need the visible plugin, and this little piece of code right here:

    $(window).scroll(function() {
        $('video').each(function() {
            if ($(this).visible(true)) {
                $(this)[0].play();
            } else {
                $(this)[0].pause();
            }
        })
    });
    

    This will allow any video to play only when it gets into viewport. By replacing visible( true ) by visible() , you can set it to play only when the entire video DOM element is in viewport.

提交回复
热议问题