简体   繁体   English

Javascript的粘边栏问题

[英]Sticky sidebar issue with Javascript

I am trying to implement a sticky sidebar that always sits at the top of the window as the user scrolls down the page. 我试图实现一个粘性侧边栏,当用户向下滚动页面时,该侧边栏始终位于窗口顶部。

I have it sticking to the top at the correct time, but for some reason it no longer floats left... will anybody please let me know what I can do to get it to stay in the same position when sticking? 我在正确的时间将其粘贴到顶部,但是由于某种原因它不再漂浮了……有人请让我知道我可以怎么做才能使其在粘贴时保持在同一位置?

My site is here . 我的网站在这里 Thanks in advance! 提前致谢!

<script type="text/javascript">
$(function(){ // document ready

    if (!!$('.sticky').offset()) { // make sure ".sticky" element exists
        var stickyTop = $('.sticky').offset().top; // returns number 
        $(window).scroll(function(){ // scroll event
            var windowTop = $(window).scrollTop(); // returns number 
            if (stickyTop < windowTop){
                $('.sticky').css( { position:'fixed', top: 0, marginLeft: "30px" } );
            }
            else {
                $('.sticky').css('position','static');
            }
        });
    }

});
</script>

Don't invent the wheel. 不要发明轮子。 Just get something like this plug-in and enjoy. 只需获得类似此插件的内容即可享受。

You don't seem to be telling it to be at the left side of the screen. 您似乎并没有告诉它在屏幕的左侧。

Try changing this line to: 尝试将此行更改为:

$('.sticky').css( { position:'fixed', top: 0, left:0, marginLeft: "30px" }

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

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