简体   繁体   English

jQuery粘性侧边栏失败:将侧边栏丢出位置

[英]jQuery sticky sidebar failing: throws sidebar out of position

Hello guys I am trying to make a sticky sidebar but it isn't working how I want it to work. 大家好,我正在尝试制作一个粘滞的侧边栏,但是我希望它不能正常工作。 Any help would be much appreciated. 任何帮助将非常感激。 What happens when you scroll is that the sidebar gets thrown out of his left position. 滚动时发生的是,侧边栏被甩出了他的左侧位置。 As you can see in the fiddle the same happens only here I am using an image. 正如您在小提琴中看到的那样,同样的情况仅在我使用图像的情况下发生。 Here is a Js fiddle . 这是一个小提琴 Any ideas what I am doing wrong or how I can make this work? 有什么想法我做错了或如何做这项工作?

Thanks in advance! 提前致谢!

jQuery code jQuery代码

jQuery(function() { // document ready
        var sideBarTop = $('#sidebar').offset().top;
        var sideBarLeft = $('#sidebar').offset().left
        jQuery(window).scroll(function(){ // scroll event
            var windowTop = $(window).scrollTop(); 
            if(sideBarTop < windowTop) {
                $('#sidebar').css({position: 'fixed', top: 0, left: sideBarLeft});
            }
            else {
                $('#sidebar').css('position', 'static');
            }
        });

    });

This issue is due to the percentage value you've set on the #sidebar . 此问题是由于您在#sidebar上设置的百分比值引起的。 When it's static the percentage value will be based on its parent element however when you switch to position:fixed the percentages will be based on the window/viewport , you can see the spec here: http://www.w3.org/TR/CSS2/visuren.html#positioning-scheme 静态时,百分比值将基于其父元素,但是当您切换到position:fixed百分比将基于window/viewport ,您可以在此处查看规格: http : //www.w3.org/TR /CSS2/visuren.html#positioning-scheme

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

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