简体   繁体   English

可见性恢复为“可见”:仅在之前不暂停的情况下自动播放视频

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

I can pause a video when visibity is changed to hidden, and play the video when visibility is back to visible. 当可见性更改为隐藏时,我可以暂停视频,而可见性恢复到可见时,可以播放视频。 Like that : 像那样 :

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

But if the video is already on pause before visibility goes to hidden, I don't want the video to play when I go back to visible. 但是,如果视频在可见性变为隐藏状态之前已经暂停,那么我不希望在返回可见状态时播放视频。

Is that possible ? 那可能吗 ? I'm not sure. 我不确定。

You can store it in a variable such as var userManuallyPause = false , and if the user pauses it him/herself, you can set that variable to true. 您可以将其存储在变量中,例如var userManuallyPause = false ,如果用户自己将其暂停,则可以将该变量设置为true。 When the user unpauses, you can set it back to false. 用户取消暂停时,可以将其设置回false。

Then in your code above, you add a check of 然后在上面的代码中,添加对

if (!userManuallyPause) { ... }

and it should run as expected. 它应该按预期运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM