Play HTML5 Video when scrolled to

前端 未结 4 2292
暖寄归人
暖寄归人 2020-12-02 17:14

Is there anyway to autoplay a HTML5 video only when the user has the video (or a certain percentage of the video) in the browser viewport?

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 17:55

    hope this helps but it has been answered before

    http://jsfiddle.net/jAsDJ/

    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);
    

提交回复
热议问题