vue 手機物理監聽鍵+退出提示代碼
我就廢話不多說了,大家還是直接看代碼吧~
<script>//Toast 這些都是在網上粘的別人的。但是找不到出處了,大佬見諒。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(’backbutton’, function (evt) {console.log(’監聽按鈕’);var url = location.hash.split(’/’)[1];if (url === ’home’ ) {// 處于app首頁,滿足退出app操作console.log(’滿足條件’)if (new Date() - time < 2000) {// 小于2s,退出程序navigator.app.exitApp();} else { // 大于2s,重置時間戳,time = new Date();Toast(’再次點擊退出’, 2000);}return;} else {console.log(’不滿足條件’)history.back(); // 不滿足退出操作,,返回上一頁}}, false);}, 10)</script>
代碼很簡單,邏輯也不是很復雜。但是要說一下為什么要用setTime( )。
我是在vue的index.html里面加的這些代碼。在沒有添加setTime()的時候不知道為啥他不執行,檢查好幾遍也沒有錯。最后請教的大佬,他也不知道為什么。/笑哭 不過能用了。
之前也遇到了一個關閉手機端虛擬鍵盤的操作。他就是不執行.。
document.activeElement.blur()
后來也是用settime( )解決的。
補充知識:Vue 單頁面處理手機返回鍵問題
在用Vue開發單頁面App時候,有時會遇到要處理返回按鍵的邏輯,讓它不是返回默認的上一級頁面,而是轉到指定的頁面。 百度了查了一下,網上給的方法基本都是通過監聽“popstate”,并不能完美解決。后來想到了Router的“導航守衛”,在離開時進行處理一下即可。話不多說,直接上例子:
beforeRouteLeave (to, from, next) { if(this.success){ next({path:’/home’});//重定向到指定路徑 }else{ next() } }
就是在next()方法里面重定向就行。完美解決,還不用綁定監聽再解綁監聽。
以上這篇vue 手機物理監聽鍵+退出提示代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: