无法使用 window.scrollTo(0,content_scroll_pos);使窗口滚动到所需位置

cannot make window scroll to desired position with window.scrollTo(0,content_scroll_pos);

本文关键字:窗口 滚动 位置 pos scroll scrollTo window content      更新时间:2023-09-26

我手头有一个非常简单的任务,但有些东西无法正常工作:|

有一个按钮可以打开全屏菜单,淡出所有其他内容。还有另一个按钮可以关闭菜单并淡入内容。

但菜单窗口高度可能与内容高度大不相同。因此,当用户单击打开菜单时,他会跳到窗口顶部。但是当用户关闭窗口时,他应该返回到原始窗口滚动位置(正是单击打开菜单的位置)。

到目前为止,我有这个*window.scrollTo(0,content_scroll_pos);不起作用!好吧,它跳到 0 0。但鉴于我知道content_scroll_pos变量不是 0。

//Content window position, before calling menu
var content_scroll_pos;
//Show menu
$("#open_nav").on("click", function(){
    //
    content_scroll_pos = $(document).scrollTop();
    //
    $("#grid_index, #sidebar-big").fadeOut("fast", function(){
        window.scrollTo(0,0);
        $("nav").fadeIn();
    });
    return false;
});
//Hide menu
$("#close_nav").on("click", function(){
    $("nav").fadeOut("fast", function(){
        window.scrollTo(0,content_scroll_pos);
        $("#grid_index, #sidebar-big").fadeIn();
    });
    return false;
});

通过重新排列事件来修复问题:

//Content window position, before calling menu
var content_scroll_pos;
//Show menu
$("#open_nav").on("click", function(){
    //
    content_scroll_pos = $(window).scrollTop();
    //
    $("#grid_index, #sidebar-big").fadeOut("fast", function(){
        window.scrollTo(0,0);
        $("nav").fadeIn("fast");
    });
    return false;
});
//Hide menu
$("#close_nav").on("click", function(){
    $("nav").fadeOut("fast", function(){
        $("#grid_index, #sidebar-big").fadeIn("fast");
        window.scrollTo(0,content_scroll_pos);
    });
    return false;
});