转载自:/p/25ac84a839bc
好用!!!
(function (root) {var isOn = false;var scrollTop;/*** 禁止页面滚动* 不会改动滚动条位置*/function on() {if (isOn) {return;}// 特殊标识,表明开启页面滚动禁用,设置了top值,不执行scroll事件window.isScrollingByNoscroll = true;var doc = document.documentElement;scrollTop = window.pageYOffset;doc.style.position = 'fixed';doc.style.top = -scrollTop + 'px';doc.style.left = 0;doc.style.right = 0;// 当数据较少页面高度有限时,可能出现弹层被截断,故注释掉overflow,暂未发现有什么影响// doc.style.overflow = 'hidden';isOn = true;}/*** 恢复页面滚动* 会自动恢复之前的滚动条位置*/function off() {if (!isOn) {return;}window.isScrollingByNoscroll = false;var doc = document.documentElement;doc.style.position = '';doc.style.top = '';doc.style.overflow = '';window.scroll(0, scrollTop);isOn = false;}/*** 判断当前是否处于禁止滚动状态* 例如:当 !noscroll.isActive() 时才允许触发下拉刷新操作*/function isActive() {return isOn;}root.noscroll = {on: on,off: off,isActive: isActive};})(window);