使用场景
1. 弹出弹窗时,隐藏右侧滚动条,并锁定页面,禁止弹窗下的页面滚动
2. 网页较长时,用户可以临时锁定当前浏览的位置,避免页面意外滚动到其他位置
核心代码
锁定页面,禁止滚动(实现原理:用overflow 'hidden' 消除滚动条,并用等宽的透明右边框填充,避免页面可用宽度变化,引起布局改变)
lockScroll() { let widthBar = 17, root = document.documentElement; if (typeof window.innerWidth == 'number') { widthBar = window.innerWidth - root.clientWidth; } root.style.overflow = 'hidden'; root.style.borderRight = widthBar + 'px solid transparent'; },
解锁页面,恢复滚动
unlockScroll() { let root = document.documentElement; root.style.overflow = ''; root.style.borderRight = ''; }
完整范例代码
<template> <div style="height: 3000px"> <div class="operationPanel"> <button @click="lockScroll">锁定页面,禁止滚动</button> <button @click="unlockScroll">解锁页面,恢复滚动</button> </div> </div> </template> <script> export default { methods: { lockScroll() { let widthBar = 17, root = document.documentElement; if (typeof window.innerWidth == 'number') { widthBar = window.innerWidth - root.clientWidth; } root.style.overflow = 'hidden'; root.style.borderRight = widthBar + 'px solid transparent'; }, unlockScroll() { let root = document.documentElement; root.style.overflow = ''; root.style.borderRight = ''; } }, } </script> <style scoped> .operationPanel { position: fixed; left: 10px; top: 10px } </style>