vue中移動端禁止頁面滑動穿透
1 通過樣式
// 禁止滾動
stop () {
var mo = function (e) {
e.preventDefault()
}
let cssStr = 'overflow-y: hidden; height: 100%;'
document.getElementsByTagName('body')[0].style.cssText = cssStr
document.documentElement.style.height = '100%'
document.documentElement.style.overflow = 'hidden'
document.body.style.cssText = cssStr
document.addEventListener('touchmove', mo, false) // 禁止頁面滑動
},
// 取消滑動限制
move () {
var mo = function (e) {
e.preventDefault()
}
let cssStr = 'overflow-y: auto; height: auto;'
document.getElementsByTagName('body')[0].style.cssText = cssStr
document.documentElement.style.overflow = 'scroll'
document.body.style.cssText = cssStr
document.removeEventListener('touchmove', mo, false)
},
缺點: 每次禁止滾動之後,頁面都會跑到最上面,不會保留滑動的位置
2 阻止默認事件 @touchmove.prevent
綁定事件@touchmove='touchEvent'
touchEvent (event) {
event.preventDefault()
}
或者直接 @touchmove.prevent
缺點: 會阻止頁面子元素的滾動事件,如果頁面有彈框,就意味着彈框的滾動事件也被禁止了
3 通過插件 tua-body-scroll-lock
$ npm i -S tua-body-scroll-lock
# OR
$ yarn add tua-body-scroll-lock
import { lock, unlock } from 'tua-body-scroll-lock'
const targetElement = document.querySelector('#content')//需要滾動的元素
lock(targetElement)//禁止滾動
unlock(targetElement)//恢復滾動
以上三種方法,基本能滿足需求啦