Test in JQuery if an element is at the top of screen

后端 未结 5 1450
予麋鹿
予麋鹿 2020-12-23 11:42

I have a div that is positioned about 100px from the top of the browser window. When the user scrolls down, I want the div to stay where it is

5条回答
  •  佛祖请我去吃肉
    2020-12-23 12:23

    when you have header. and then aside bar. for fixing aside bar, when it is at top of the screen:

    Javascript:

    var scroll_happened = false;
    var aside_from_top = $('aside').offset().top;
    $window = $(window);
    
    $window.scroll(function()
    {
        scroll_happened = true;
    });
    
    setInterval(function()
    {
        if(scroll_happened == true)
        {
            scroll_happened = false;
            if($window.scrollTop() >= aside_from_top)
            {
                $('#aside_container').addClass('fixed_aside');
            }
            else
            {
                $('#aside_container').removeClass('fixed_aside');
            }
        }
    } , 250);
    

    Css:

    .fixed_aside
    {
        position: fixed;
        top: 0;
        bottom: 0;
    }
    

    Html:

    
    

提交回复
热议问题