可见度恢复到':视频自动播放,如果之前没有暂停

visibility back to 'visible' : video auto-play only if was not on pause before

本文关键字:如果 暂停 自动播放 视频 恢复 可见度      更新时间:2023-09-26

我可以在可见度变为隐藏时暂停视频,在可见度恢复为可见时播放视频。像这样:

    var userManuallyPause = false;
    var video = document.getElementById('video');
    var documentTitle = document.title;
    var updateTitleForVideo = function(state){
        if (state === '') {
            document.title = documentTitle;
            return;
        };
        document.title = documentTitle + ' [' + state + ']';
    };
    video.onpause = function(){
        userManuallyPause = true;
        updateTitleForVideo('Paused');
    };
    video.onplay = function(){
        updateTitleForVideo('');
    };
    document.addEventListener('visibilitychange', function(){
        var state = document.visibilityState;
        if (!video.paused) {
            if (state === 'hidden') {
                video.pause();
                userManuallyPause = false;
                updateTitleForVideo('Paused');
            }
        }
        else if (state === 'visible' && !userManuallyPause) { video.play(); }
    });

但是,如果视频在可见度变为隐藏之前已经暂停,我不希望视频在我返回可见时播放。

这可能吗?我不确定。

您可以将其存储在一个变量中,例如var userManuallyPause = false,如果用户自己暂停,您可以将该变量设置为true。当用户解除暂停时,您可以将其设置回false。

然后在上面的代码中,添加

检查
if (!userManuallyPause) { ... }
相关文章: