在后续访问时将 HTML5 视频静音

Mute HTML5 video on subsequent visit

本文关键字:HTML5 视频 访问      更新时间:2023-09-26

我正在使用Reveal Modal (http://zurb.com/playground/reveal-modal-plugin)仅在访问者第一次访问时触发一个modal弹出框,并使用jQuery Cookie(https://github.com/carhartl/jquery-cookie)设置cookie

这是模态的代码(在移动设备上显示 GIF):

<div id="myModal" class="reveal-modal">
</div>
<script type="text/javascript">
    var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/);
    var myModal = document.getElementById('myModal');
    if(!isMobile) {
    // User-Agent is not IPhone, IPod, IPad, Android or BlackBerry
    myModal.innerHTML += '<video autoplay>' +
    '<source src="video/LogoOpening.mp4" type="video/mp4"/>' +
    '<source src="video/LogoOpening.ogg" type="video/ogg"/>' +
    '<source src="video/LogoOpening.webm" type="video/webm"/>' +
    '</video>' +
    '<a class="close-reveal-modal"><div class="button4">Close</div></a>';
    } else {
    myModal.innerHTML += '<img src="images/ThroughTheYears.gif" alt="Logo History" />' +
    '<a class="close-reveal-modal"><div class="button4">Close</div></a>' +
    '</div>';
    }
</script>

。这是在检查cookie后触发模态的Javascript:

<script>
    $(document).ready(function() {
    if ($.cookie('modal_shown') == null) {
        $.cookie('modal_shown', 'yes', { expires: 30, path: '/' });
        $('#myModal').reveal({
         animation: 'fade',                         //fade, fadeAndPop, none
         animationspeed: 500,                       //how fast animtions are
         closeonbackgroundclick: true,              //if you click background will modal close?
         dismissmodalclass: 'close-reveal-modal'    //the class of a button or element that will close an open modal
         });
    }
    });
</script>

所以,问题来了:当我的访问者第一次出现时,视频会完美地触发并自动播放,就像它应该的那样(类似的动画 GIF 仅在移动设备上播放);但是,视频有声音,在随后的访问中,视频会自动播放,您会听到音频,但模态不会在视觉上触发(模态和视频保持隐藏)。

我认为解决方案是以某种方式将视频的静音属性与 cookie 检查 Javascript(它确定模态是否触发)联系起来,但我不确定如何编码。帮助?

这样的东西应该可以工作

if (!isMobile) {
    // User-Agent is not IPhone, IPod, IPad, Android or BlackBerry
    if ($.cookie('modal_shown') == null) {
        myModal.innerHTML += '<video autoplay controls>'
    } else {
        myModal.innerHTML += '<video autoplay muted controls>'
    }
    myModal.innerHTML += '<source src="video/LogoOpening.mp4" type="video/mp4"/>' +
    ....
    ....
    '</video>' +

。添加对 cookie model_shown的额外检查允许您更改视频是否会自动播放,或者会自动播放但被静音(如果您不希望它自动播放,您可以将其删除,在这种情况下,可能也不需要静音。我还添加了controls,以便用户可以根据需要手动控制音量或播放/暂停

希望这有帮助(如果不是你需要的只是评论,我会尝试靠近)