简体   繁体   English

滚动时固定侧栏的计算

[英]Calculation for sidebar fixed when scrolling

I am using position absolute to have a sidebar stick to the viewable top of a parent div. 我使用position绝对有一个侧边栏粘贴到父div的可见顶部。 For example. 例如。 Parent DIV is located at X:20% and Y:20% of the entire screen. 父DIV位于整个屏幕的X:20%和Y:20%。 Inside Parent Div I have a sidebar DIV positioned absolute that is set to Top:0 and Right:0. Inside Parent Div我有一个侧边栏DIV,其绝对值设置为Top:0和Right:0。

As the parent div scrolls I increase the margin-top so that is always stays at the top of viewable area. 当父div滚动时,我增加margin-top,以便始终保持在可视区域的顶部。 I have been struggling with the calculation for this and just can't seem to get the difference between pageOffset, scollTop, etc. I have been thru w3schools and it still isn't making sense. 我一直在努力计算这个,似乎无法得到pageOffset,scollTop等之间的区别。我已经通过w3schools,它仍然没有意义。

Here is the calculation I have so far but for some reason in IE the sidebar jumps. 这是我到目前为止的计算但由于某些原因在IE中侧边栏跳跃。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks in advance 提前致谢

var s = $(".sidebar");
var pos = s.position();
$(window).scroll(function () {
    var windowpos = $(window).scrollTop();
    (windowpos >= 270) ? s.css("marginTop", Math.floor($(window).scrollTop() - 270) + "px") : s.css("marginTop", 0);
});

If i understand correctly this should be a good example: 如果我理解正确,这应该是一个很好的例子:

var s = $(".sidebar");
var pos = s.offset().top;

    $(window).scroll(function () {
        if ($(window).scrollTop() >= pos) {
            s.addClass('new-styles');
        } else {
            s.removeClass('new-styles');
        }
    });

the styles: 风格:

.sidebar {
    position: absolute; // or relative
    top: 100px;
}
.new-styles {
    position: fixed;
    top: 0;
}

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

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