css实用技巧——锁定页面,禁止滚动 vs 解锁页面,恢复滚动

使用场景

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>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝阳39

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值