方法一:IOS 允许滚动会无效
function scrControl (t) {
if (t === 0) { // 禁止滚动
document.body.addEventListener('touchmove', function (e) {
e.preventDefault()
}, { passive: false }) // passive 参数不能省略,用来兼容 IOS 和 Android
} else if (t === 1) { // 允许滚动
document.body.addEventListener('touchmove', function (e) {
e.returnValue = true
}, { passive: false })
}
}
passive,设置该属性的目的主要是为了在阻止事件默认行为导致的卡顿。等待监听器的执行是耗时的,有些甚至耗时很明显,这样就会导致页面卡顿。即便监听器是个空函数,也会产生一定的卡顿,毕竟空函数的执行也会耗时。加上 { passive: false } 能防止页面卡顿。
可以通过传递 passive 为 true 来明确告诉浏览器,事件处理程序不会调用 preventDefault 来阻止默认滑动行为。
如果设置了 passive 为 true,同时又阻止默认行为,阻止是不生效的。
document.addEventListener('touchmove', function (event) {
event.preventDefault() // 不产生作用
}, { passive: true })
方法二:兼容 IOS
function bodyScroll (event) {
event.preventDefault()
}
function scrControl (t) {
if (t === 0) { // 禁止滚动
document.body.addEventListener('touchmove', this.bodyScroll, { passive: false })
} else if (t === 1) { // 开启滚动
document.body.removeEventListener('touchmove', this.bodyScroll, { passive: false })
}
}