如何使用 jQuery 以编程方式禁用页面滚动 [英] How to programmatically disable page scrolling with jQuery

查看:53
本文介绍了如何使用 jQuery 以编程方式禁用页面滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 jQuery,我想禁用主体的滚动:

Using jQuery, I would like to disable scrolling of the body:

我的想法是:

  1. 设置 body{ overflow: hidden;}
  2. 捕获当前scrollTop();/scrollLeft()
  3. 绑定到 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:

  1. 获取当前滚动位置(不要忘记水平轴!).
  2. 将溢出设置为隐藏(可能是想保留之前的溢出值).
  3. 使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆