HTML5 and Javascript to play videos only when visible

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

    OK, I think, it must be something like this:

    var videos = document.getElementsByTagName("video");
    
    function checkScroll() {
        var fraction = 0.8; // Play when 80% of the player is visible.
    
        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);
    

提交回复
热议问题