如何使用 jQuery 以编程方式禁用页面滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3656592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:50:44  来源:igfitidea点击:

How to programmatically disable page scrolling with jQuery

jquerycssscroll

提问by Hailwood

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

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

My idea is to:

我的想法是:

  1. Set body{ overflow: hidden;}
  2. Capture the current scrollTop();/scrollLeft()
  3. Bind to the body scroll event, set scrollTop/scrollLeft to the captured value.
  1. body{ overflow: hidden;}
  2. 捕获当前 scrollTop();/scrollLeft()
  3. 绑定到 body 滚动事件,设置 scrollTop/scrollLeft 为捕获的值。

Is there a better way?

有没有更好的办法?



Update:

更新:

Please see my example, and a reason why, at http://jsbin.com/ikuma4/2/edit

请在http://jsbin.com/ikuma4/2/edit 上查看我的示例以及原因

I am aware someone will be thinking "why does he not just use position: fixedon the panel?".

我知道有人会想“为什么他不只是position: fixed在面板上使用?”。

Please do not suggest this as I have other reasons.

请不要建议这样做,因为我还有其他原因。

采纳答案by tfe

The only way I've found to do this is similar to what you described:

我发现这样做的唯一方法与您描述的类似:

  1. Grab current scroll position (don't forget horizontal axis!).
  2. Set overflow to hidden (probably want to retain previous overflow value).
  3. Scroll document to stored scroll position with scrollTo().
  1. 获取当前滚动位置(不要忘记水平轴!)。
  2. 将溢出设置为隐藏(可能是想保留之前的溢出值)。
  3. 使用 scrollTo() 将文档滚动到存储的滚动位置。

Then when you're ready to allow scrolling again, undo all that.

然后,当您准备好再次滚动时,撤消所有操作。

Edit: 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])

回答by gitaarik

This will completelydisable scrolling:

这将完全禁用滚动:

$('html, body').css({
    overflow: 'hidden',
    height: '100%'
});

To restore:

恢复:

$('html, body').css({
    overflow: 'auto',
    height: 'auto'
});

Tested it on Firefox and Chrome.

在 Firefox 和 Chrome 上对其进行了测试。

回答by cubbiu

try this

尝试这个

$('#element').on('scroll touchmove mousewheel', function(e){
  e.preventDefault();
  e.stopPropagation();
  return false;
})

回答by mr.soroush

you can use this code:

您可以使用此代码:

$("body").css("overflow", "hidden");

回答by JeanValjean

I just provide a little tuning to the solution by tfe. In particular, I added some additional control to ensure that there is no shifting of the page content(aka page shift) when the scrollbar is set to hidden.

我只是通过tfe对解决方案进行了一些调整。特别是,我添加了一些额外的控件,以确保当滚动条设置为 时,页面内容(又名page shift不会发生移动hidden

Two Javascript functions lockScroll()and unlockScroll()can be defined, respectively, to lock and unlock the page scroll.

两个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});
}

where I assumed that the <body>has no initial margin.

我假设<body>没有初始保证金。

Notice that, while the above solution works in most of the practical cases, it is not definitive since it needs some further customization for pages that include, for instance, an header with position:fixed. Let's go into this special case with an example. Suppose to have

请注意,虽然上述解决方案适用于大多数实际情况,但它并不是确定的,因为它需要对包含position:fixed. 让我们通过一个例子来探讨这个特殊情况。假设有

<body>
<div id="header">My fixedheader</div>
<!--- OTHER CONTENT -->
</body>

with

#header{position:fixed; padding:0; margin:0; width:100%}

Then, one should add the following in functions lockScroll()and unlockScroll():

然后,应该在函数lockScroll()和中添加以下内容unlockScroll()

function lockScroll(){
    //Omissis   


    $('#header').css('margin-right', marginR);
} 

function unlockScroll(){
    //Omissis   

    $('#header').css('margin-right', 0);
}

Finally, take care of some possible initial value for the margins or paddings.

最后,注意边距或填充的一些可能的初始值。

回答by Patrick DaVader

To turn OFF scrolling try this:

要关闭滚动试试这个:

var current = $(window).scrollTop();
$(window).scroll(function() {
    $(window).scrollTop(current);
});

to reset:

重置:

$(window).off('scroll');

回答by dzimi

You can attach a function to scroll events and prevent its default behaviour.

您可以附加一个函数来滚动事件并防止其默认行为。

var $window = $(window);

$window.on("mousewheel DOMMouseScroll", onMouseWheel);

function onMouseWheel(e) {
    e.preventDefault();
}

https://jsfiddle.net/22cLw9em/

https://jsfiddle.net/22cLw9em/

回答by Josh Harrison

I've written a jQuery plugin to handle this: $.disablescroll.

我写了一个 jQuery 插件来处理这个:$.disablescroll

It prevents scrolling from mousewheel, touchmove, and keypress events, such as Page Down.

它可以防止鼠标滚轮、触摸移动和按键事件(例如Page Down.

There's a demo here.

这里有一个演示

Usage:

用法:

$(window).disablescroll();

// To re-enable scrolling:
$(window).disablescroll("undo");

回答by Pawel

One liner to disable scrolling including middle mouse button.

一种禁用滚动的衬垫,包括鼠标中键。

$(document).scroll(function () { $(document).scrollTop(0); });

edit: There's no need for jQuery anyway, below same as above in vanilla JS(that means no frameworks, just JavaScript):

编辑:无论如何都不需要jQuery,在vanilla JS中与上面相同(这意味着没有框架,只有JavaScript):

document.addEventListener('scroll', function () { this.documentElement.scrollTop = 0; this.body.scrollTop = 0; })

this.documentElement.scrollTop - standard

this.documentElement.scrollTop - 标准

this.body.scrollTop - IE compatibility

this.body.scrollTop - IE 兼容性

回答by Joan Alberto Aguilar Pe?a

  • To Hide Scroll: $("body").css("overflow", "hidden");
  • To Restore Scroll: $("body").css("overflow", "initial");
  • 隐藏滚动: $("body").css("overflow", "hidden");
  • 恢复滚动: $("body").css("overflow", "initial");