Triggering a video autoplay based on scroll position

前端 未结 3 1962
醉梦人生
醉梦人生 2020-12-25 10:08

I am writing a script that uses the Wipe animation from the scrollorama.js script. I am hoping to be able to implement a video to autoplay at certain markers in the scroll d

3条回答
  •  悲哀的现实
    2020-12-25 10:35

    just add the script from below and add playonscroll param to your video tag anywhere on a page.

    As well some times it's required to use different scroll container than body, sometimes its not obvious, so the following code works like a charm for me:

    setInterval(function () {
        $('video[playonscroll]').each(function () {
            var videoElement = $(this)[0]; 
            var eTop = $(this).offset().top;
            var elementOffestY = (eTop - $(window).scrollTop());
            var videoOffset = [elementOffestY, elementOffestY+$(this).height()];
            if ((videoOffset[0] < 100) && (videoOffset[1] > 350)) {
                console.log('play');
                if (!videoElement.playing) {
                    videoElement.play();
                }
            } else {
                if (videoElement.playing) {
                    videoElement.pause();
                }
            }
        });
    },300);
    

    in case if you always use body container for scroll just change setInterval to $(window).scroll

    And don't forget to define property for Video tag element:

    Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
        get: function(){
            return (this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
        }
    })
    

提交回复
热议问题