页签隐藏展示来监听原生返回

需求:APP内页面音频播放时,原生app的返回或者安卓ios的物理键返回返回时,暂停音频播放。

方法:浏览器标签页被隐藏或显示的时候会触发visibilitychange事件.点击查看介绍

例子:当你切换到另一个标签时视频会暂停,当你返回到当前标签时视频会再次播放

音频例子

html

<div style="background:#eca2a2;min-height:80px;margin-top:20px;">
    <audio id="audio" controls>
        <source src="./p3.mp3" type="audio/mp3">
        您的浏览器不支持 audio 元素。
     </audio>
</div>

js

// 监听页面是否可见
// 设置隐藏属性和改变可见属性的事件的名称
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
    hidden = "hidden";
    visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden";
    visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
    visibilityChange = "webkitvisibilitychange";
}

var videoElement = document.getElementById("audio");
function handleVisibilityChange() {
   if (document[hidden]) {
        alert('要关闭')
        videoElement.pause();
    }

}

当音频是多个的时候

html

<div id="audio-bar">
      <audio controls>
         <source src="./p3.mp3" type="audio/mp3">
            您的浏览器不支持 audio 元素。
      </audio>
        <audio controls>
         <source src="./p3.mp3" type="audio/mp3">
            您的浏览器不支持 audio 元素。
      </audio>
       <audio controls>
         <source src="./p3.mp3" type="audio/mp3">
            您的浏览器不支持 audio 元素。
      </audio>
</div>

js

// 如果页面是隐藏状态,则暂停音频
function handleVisibilityChange() {
    // if (document[hidden]) {
    //     alert('要关闭')
    //     videoElement.pause();
    // } else {
    //     //  videoElement.play();
    // }
    var domList = document.querySelectorAll('audio');
    console.log(domList)
    for (var i = 0;i < domList.length;i++) {
        domList[i].pause()
    }
}

// 如果浏览器不支持addEventListener 或 Page Visibility API 给出警告
if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") {
    console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {

    // 处理页面可见属性的改变
    document.addEventListener(visibilityChange, handleVisibilityChange, false);

    
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值