通用锁屏方法,原理即锁定/解锁容器滚动,原生代码,引入即可使用,初始化只需执行一次,具体使用方法详见代码顶部的注释
/**
* 锁屏
* 示例:
* var l = new ScrollLock();
* 或 var l = new ScrollLock(document.querySelector('#scroll-container'));
* 或 var l = new ScrollLock($('#scroll-container'))
* 锁屏 || 解锁
* l.lock() || l.unlock();
* @param {dom} element dom节点(不填默认body,可以是jq节点)
*/
function ScrollLock(element) {
this.scrollBox = !element ? document.body : element.length ? element[0] : element instanceof HTMLElement ? element : document.body;
this.isWindow = this.scrollBox == document.body;
this.Fixedtop = '';
this.overflow = this.position = '';
}
ScrollLock.prototype.lock = function() { //加锁
this.Fixedtop = this.isWindow ? window.scrollY : this.scrollBox.scrollTop;
this.overflow = this.getStyle('overflow') || 'initial';
this.position = this.getStyle('position');
this.scrollBox.style.position = 'fixed';
this.scrollBox.style.overflow = 'hidden';
this.scrollBox.style.top = (this.isWindow ? -this.Fixedtop : 0) + 'px';
}
ScrollLock.prototype.unlock = function() { //解锁
this.scrollBox.style.position = this.position;
this.scrollBox.style.top = 0;
this.scrollBox.style.overflow = this.overflow;
(this.isWindow ? window : this.scrollBox).scrollTo(0, this.Fixedtop)
}
ScrollLock.prototype.getStyle = function(prop) {
if(window.getComputedStyle) {
return window.getComputedStyle(this.scrollBox)[prop];
} else {
return this.scrollBox.currenrStyle[prop];
}
}