简体   繁体   English

移动div与窗口滚动不一致

[英]Move div with window scroll not consistent

I need my sidebar to scroll up and down with the window but stop when the div is at its top or bottom. 我需要边栏在窗口中上下滚动,但是在div处于顶部或底部时停止。 The code below works when the page is first loaded and scrolled down or when the page is scrolled up slowly, but when the page is scrolled to the very bottom of the sidebar div, the page has to reach the top (and then some) in order to trigger that margin change. 下面的代码在第一次加载页面并向下滚动或页面缓慢向上滚动时起作用,但是当页面滚动到侧边栏div的最底部时,页面必须到达页面顶部(然后是某些页面)。为了触发该保证金变更。

Is there some other trigger I should be looking for besides just on scroll? 除了滚动之外,我还应该寻找其他触发器吗? How can I adjust this code to properly adjust the div? 如何调整此代码以正确调整div?

$(window).on("load scroll", function() {
    var scrollYpos = $(document).scrollTop();
    var sidebarinfo = $("#sidebar").offset().top + $("#sidebar").height();
    var windowinfo = $(window).height() + $(window).scrollTop();
    if ((windowinfo)<(sidebarinfo)){
        $('#sidebar').css('margin-top', -scrollYpos);
    }
});

The sidebar div is fixed position. 侧栏div是固定位置。 If I use absolute position, the div scrolls fine, but it doesn't stop when the bottom of the div has been reached - it just continues to scroll with the window. 如果我使用绝对位置,则div可以很好地滚动,但是到达div的底部时它不会停止-它将继续随窗口滚动。


I've fixed the main part of the problem with this code. 我已使用此代码修复了问题的主要部分。

$(window).on("load scroll", function() {
    var sidebarinfo = $("#sidebar").scrollTop() + $("#sidebar").height();
    var windowinfo = $(window).innerHeight() + $(window).scrollTop();
    if ((windowinfo)<(sidebarinfo)){
        $('#sidebar').css('top', -($(window).scrollTop()));
    }
});

The only problem is on page load, the sidebar gets stuck in the wrong position until it is scrolled all the way up (and more). 唯一的问题是页面加载,侧边栏卡在错误的位置,直到完全向上滚动(以及更多)。

I actually figured out that I needed to adjust a few things and add an else clause: 我实际上发现我需要调整一些内容并添加else子句:

$(window).on("scroll", function() {
    var scrollmargin = $(window).scrollTop() - $("#sidebar").outerHeight();
    var sidebarinfo = $("#sidebar").scrollTop() + $("#sidebar").outerHeight();
    var windowinfo = $(window).innerHeight() + $(window).scrollTop();
    console.log($(window).scrollTop());
    if ((windowinfo)<(sidebarinfo)){
        $('#sidebar').css('top', (sidebarinfo + scrollmargin)*-1);
    }
    else {
        var margintop = $(window).innerHeight() - $("#sidebar").outerHeight();
        $('#sidebar').css('top', margintop);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM