我只是对tfe 的解决方案进行了一些调整。特别是,我添加了一些额外的控件,以确保当滚动条设置为 hidden 时,页面内容不会移动(又名 page shift)。
可以分别定义两个Javascript函数lockScroll()和unlockScroll()来锁定和解锁页面滚动。
function lockScroll(){
$html = $('html');
$body = $('body');
var initWidth = $body.outerWidth();
var initHeight = $body.outerHeight();
var scrollPosition = [
self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
];
$html.data('scroll-position', scrollPosition);
$html.data('previous-overflow', $html.css('overflow'));
$html.css('overflow', 'hidden');
window.scrollTo(scrollPosition[0], scrollPosition[1]);
var marginR = $body.outerWidth()-initWidth;
var marginB = $body.outerHeight()-initHeight;
$body.css({'margin-right': marginR,'margin-bottom': marginB});
}
function unlockScroll(){
$html = $('html');
$body = $('body');
$html.css('overflow', $html.data('previous-overflow'));
var scrollPosition = $html.data('scroll-position');
window.scrollTo(scrollPosition[0], scrollPosition[1]);
$body.css({'margin-right': 0, 'margin-bottom': 0});
}
我假设<body> 没有初始边距。
请注意,虽然上述解决方案在大多数实际情况下都有效,但它并不确定,因为它需要对页面进行一些进一步的定制,例如包含position:fixed 的标题。让我们用一个例子来讨论这个特殊情况。假设有
<body>
<div id="header">My fixedheader</div>
<!--- OTHER CONTENT -->
</body>
与
#header{position:fixed; padding:0; margin:0; width:100%}
然后,应该在函数lockScroll() 和unlockScroll() 中添加以下内容:
function lockScroll(){
//Omissis
$('#header').css('margin-right', marginR);
}
function unlockScroll(){
//Omissis
$('#header').css('margin-right', 0);
}
最后,注意一些可能的边距或填充的初始值。