Pause and play video when in viewport

后端 未结 3 1821
别那么骄傲
别那么骄傲 2021-01-17 05:43

I was experimenting with play and pause when a video is within the viewport... when I was searching around I found the following code.. which unfortunately didn\'t work:

3条回答
  •  忘掉有多难
    2021-01-17 06:02

    I agree with what you said in your question: users might not like it, especially if they're on mobile and you're sucking all their data plan. Anyway, here's how to check if an element is in the viewport: http://jsfiddle.net/pwhjk232/

    $(document).ready(function() {
        var inner = $(".inner");
        var elementPosTop = inner.position().top;
        var viewportHeight = $(window).height();
        $(window).on('scroll', function() {
            var scrollPos = $(window).scrollTop();
            var elementFromTop = elementPosTop - scrollPos;
    
            if (elementFromTop > 0 && elementFromTop < elementPosTop + viewportHeight) {
                inner.addClass("active");
            } else {
                inner.removeClass("active");
            }
        });
    })
    

    Instead of using addClass you could use .get(0).play() and .get(0).pause() as suggested by Vohuman

提交回复
热议问题