HTML5 and Javascript to play videos only when visible

前端 未结 11 652
梦如初夏
梦如初夏 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:18

    Tried many solutions, the only one partially working is the one posted below. The problem is that having 3 videos on the page, the second one and the third one are basically controlled by the first one.

    So they start playing when the page is loaded (while they are supposed to play when in viewport) and they get paused when the first get paused, any suggestion on having this working with multiple videos?

    Tried using getElementById but didn't work, tried also jquery plugins but no good results.

    Here you have the www page where you can see what happen and all source code of course.

    http://185.197.128.183/~monompro/

    window.onload = function() {
    
        var videos = document.getElementsByTagName("video"),
            fraction = 0.8;
    
        function checkScroll() {
    
            for (var i = 0; i < videos.length; i++) {
    
                var video = videos[i];
    
                var x = video.offsetLeft,
                    y = video.offsetTop,
                    w = video.offsetWidth,
                    h = video.offsetHeight,
                    r = x + w, //right
                    b = y + h, //bottom
                    visibleX, visibleY, visible;
    
                visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
                visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
    
                visible = visibleX * visibleY / (w * h);
    
                if (visible > fraction) {
                    video.play();
                } else {
                    video.pause();
                }
    
            }
    
        }
    
        window.addEventListener('scroll', checkScroll, false);
        window.addEventListener('resize', checkScroll, false);
    }
    

提交回复
热议问题