環境:手機瀏覽器
1、visibilitychange ios Safari 不兼容
重要的就是給window加一個visibilitychange監聽,在里面判斷document.visibilityState的值,如果為hidden,則是頁面內容不可見時的鈎子,如果不是hidden,則就是可見時的鈎子,即喚醒頁面或切換應用回到頁面的回調。
vue里面使用方法可以參考以下代碼
data:() =>{ return { times:'', closeTime:'' } } mounted() { window.addEventListener('visibilitychange',this.diffTime) }, beforeDestroy(){ window.removeEventListener('visibilitychange', this.diffTime) }, methods: { // 處理鎖屏時間差 diffTime() { if (document.visibilityState =='hidden') { this.closeTime = Date.now() } else { this.times = this.times - (Date.now() - this.closeTime)/1000; } }, }
兼容性:ios不支持
2、實時記錄當前時間,比較時間差、(手機喚醒后會從新啟動定時器)
部分示例代碼:
<template> <i class="timer" v-text="msgs"></i> </template> <script> export default { name: 'Timer', props: ['time'], data () { return { msg: '', timer: null, myTime: 0, markTime: null } }, components: {}, mounted () { if (this.time) { this.myTime = this.time this.start() } else { this.msg = '00:00' } }, destroyed () { clearTimeout(this.timer) }, methods: { start () { let _this = this if (this.myTime === 0) { this.msg = '00:00' clearTimeout(this.timer) this.timer = null this.$emit('callback') } else { this.myTime-- this.timer = setTimeout(() => {
/*實現代碼 start*/ let now = Date.now() if (_this.markTime) { // let d = (now - _this.markTime) / 1000 if (d > 2) { _this.myTime = _this.myTime - d } } _this.markTime = now
/*end*/ this.start() }, 1000) } } }, } </script>
有更好處理方式請留言,互相學習!