Make element fixed on scroll

前端 未结 10 2412
臣服心动
臣服心动 2020-12-23 02:09

I\'m attempting to make the navigation bar stick to the top, when the user scrolls down to the nav bar and then unstick when the user scrolls back up past the navbar. I unde

10条回答
  •  孤城傲影
    2020-12-23 02:28

    Here you go, no frameworks, short and simple:

    var el = document.getElementById('elId');
    var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;
    
    window.addEventListener('scroll', function(){
        if (document.documentElement.scrollTop > elTop){
            el.style.position = 'fixed';
            el.style.top = '0px';
        }
        else
        {
            el.style.position = 'static';
            el.style.top = 'auto';
        }
    });
    

提交回复
热议问题