如果我将高度应用于正文,页面将滚动到顶部

The page gets scrolled to the top if I apply height to the body

本文关键字:滚动 顶部 正文 高度 应用于 如果      更新时间:2023-09-26

我的问题是我在html页面上有一个按钮,当单击此按钮时,会打开一个弹出框(覆盖背景(,并且为了停止背景滚动,我正在应用此css:

windowHeight = $(window).height();
$("body").css({
    "height": windowHeight,
    "overflow": "hidden", 
    "overflow-y": "hidden"
});

一切正常,但页面滚动到顶部。我该如何防止这种情况?

这是因为您更改了height。你不需要设置height,做body overflow: hidden应该就足够了。

.CSS:

.locked {
  overflow-x: hidden; overflow-y: hidden;
}

Javascript:

$("body").addClass("locked");

一试:http://jsbin.com/tapagexope/1/edit?html,css,js,output(点击正文(

在FF 34和Chrome 38中测试。


请注意,您应该将叠加放置在position: fixedleft, top, bottom, right0的容器中,覆盖整个视口。在该框中,您可以将叠加元素居中。

我实际上已经写了一个jQuery插件来解决这个确切的问题: jquery-disablescroll

使用插件脚本,当弹出窗口打开调用时:

$(window).disablescroll();

弹出窗口关闭后,通过调用以下命令再次启用滚动:

$(window).disablescroll("undo");

下面是示例。