手机物理返回键,一次回到上一页、连续两次退出app

mac2024-04-22  9

在网上看了很多demo,这里总结一下。(我这里是用vue写的移动端)

直接上代码吧 function Toast(msg, duration) { duration = isNaN(duration) ? 3000 : duration; var m = document.createElement('div'); m.innerHTML = msg; m.style.cssText = "width: 60%;min-width: 150px;opacity: 0.7;height: 30px;color: rgb(255, 255, 255);line-height: 30px;text-align: center;border-radius: 5px;position: fixed;bottom: 70px;left: 20%;z-index: 999999;background: rgb(0, 0, 0);font-size: 12px;"; document.body.appendChild(m); setTimeout(function () { var d = 0.5; m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in'; m.style.opacity = '0'; setTimeout(function () { document.body.removeChild(m) }, d * 1000); }, duration); } var time = '' // 用来存上一次按键时间; setTimeout(() => { // 监听返回按钮 document.addEventListener('plusready', function () { plus.key.addEventListener('backbutton', function (evt) { console.log('监听按钮'); var webview = plus.webview.currentWebview(); var url = location.hash.split('/')[1]; if (url === 'home') { // 处于app首页,满足退出app操作 console.log('满足条件') if (new Date() - time < 2000) { // 小于2s,退出程序 webview.close(); } else { // 大于2s,重置时间戳, time = new Date(); Toast('再次点击退出', 2000); } return; } else { console.log('不满足条件') history.go(-1); // 不满足退出操作,,返回上一页 } }, false); }) }, 10)

以上都是写在index.html里的,url要根据自己的项目修改。

测过,有用。 效果如下。

(本人第一次写博客,可能表达的不太好,见谅哈!!!)

最新回复(0)