Lock and unlock page scrolling
此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.greasyfork.org/scripts/589163/1889704/ScrollLocker.js
// ==UserScript==
// @name ScrollLocker
// @name:zh-CN ScrollLocker
// @namespace https://greasyfork.org/zh-CN/users/1570630
// @version 1.2
// @description Lock and unlock page scrolling
// @description:zh-CN 锁定与恢复页面滚动
// @author ryxel
// @license MIT
// ==/UserScript==
var scrollLocker = (function() {
'use strict';
if (!document.__scrollLockerData) {
document.__scrollLockerData = {
lockCount: 0,
savedStyle: null,
isMobile: null
};
}
const data = document.__scrollLockerData;
const locker = {
isLocked: false,
lock() {
if (locker.isLocked) return;
locker.isLocked = true;
if (++data.lockCount > 1) return;
if (data.isMobile === null) data.isMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent);
data.savedStyle = {
bodyOverflow: document.body.style.overflow,
bodyPaddingRight: document.body.style.paddingRight,
htmlOverflow: document.documentElement.style.overflow
};
if (data.isMobile) {
document.body.style.overflow = 'hidden';
document.documentElement.style.overflow = 'hidden';
} else {
const oldWidth = document.body.clientWidth;
const oldPaddingRight = parseFloat(window.getComputedStyle(document.body).paddingRight) || 0;
document.body.style.overflow = 'hidden';
document.documentElement.style.overflow = 'hidden';
const diff = document.body.clientWidth - oldWidth;
if (diff > 0) document.body.style.paddingRight = `${oldPaddingRight + diff}px`;
}
},
unlock() {
if (!locker.isLocked) return;
locker.isLocked = false;
if (data.lockCount <= 0) return;
if (--data.lockCount > 0) return;
document.body.style.overflow = data.savedStyle.bodyOverflow;
document.body.style.paddingRight = data.savedStyle.bodyPaddingRight;
document.documentElement.style.overflow = data.savedStyle.htmlOverflow;
data.savedStyle = null;
}
};
return locker;
})();