如何使用 jQuery 以编程方式禁用页面滚动 [英] How to programmatically disable page scrolling with jQuery
问题描述
使用 jQuery,我想禁用主体的滚动:
Using jQuery, I would like to disable scrolling of the body:
我的想法是:
- 设置
body{ overflow: hidden;}
- 捕获当前
scrollTop();/scrollLeft()
- 绑定到 body 滚动事件,设置 scrollTop/scrollLeft 为捕获的值.
有更好的方法吗?
更新:
请参阅我的示例,以及原因,在 http://jsbin.com/ikuma4/2/编辑
Please see my example, and a reason why, at http://jsbin.com/ikuma4/2/edit
我知道有人会想为什么他不只是在面板上使用 position: fixed
?".
I am aware someone will be thinking "why does he not just use position: fixed
on the panel?".
请不要提出这个建议,因为我还有其他原因.
Please do not suggest this as I have other reasons.
推荐答案
我发现的唯一方法与您描述的类似:
The only way I've found to do this is similar to what you described:
- 获取当前滚动位置(不要忘记水平轴!).
- 将溢出设置为隐藏(可能是想保留之前的溢出值).
- 使用 scrollTo() 将文档滚动到存储的滚动位置.
然后,当您准备好再次允许滚动时,撤消所有操作.
Then when you're ready to allow scrolling again, undo all that.
没有理由我不能给你代码,因为我不厌其烦地把它挖出来......
no reason I can't give you the code since I went to the trouble to dig it up...
// lock scroll position, but retain settings for later
var scrollPosition = [
self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
];
var html = jQuery('html'); // it would make more sense to apply this to body, but IE7 won't have that
html.data('scroll-position', scrollPosition);
html.data('previous-overflow', html.css('overflow'));
html.css('overflow', 'hidden');
window.scrollTo(scrollPosition[0], scrollPosition[1]);
// un-lock scroll position
var html = jQuery('html');
var scrollPosition = html.data('scroll-position');
html.css('overflow', html.data('previous-overflow'));
window.scrollTo(scrollPosition[0], scrollPosition[1])
这篇关于如何使用 jQuery 以编程方式禁用页面滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!