Floating nav bar that stops fixed to the top of the page

前端 未结 1 1157
南旧
南旧 2021-01-25 05:01

I am trying to mimic something that I have seen a few different times. There is usually a banner with a nav bar below and when the page is scrolled it moves until it touches the

相关标签:
1条回答
  • 2021-01-25 05:43

    All references to a non-existant navTopPos variable should be changed to reference the topPos variable. Your JS code should now be:

    var topPos;
    var updatedPos;
    window.onscroll = navPos;
    if (!topPos) {
        topPos = 120;
    }
    function navPos() {
        var pos = window.scrollY;
        if (!topPos) {//this line was changed
            topPos = 120;//this line was changed
        }
        var st = document.getElementById('navTest');
    
        if (st) {
            if (pos < topPos && updatedPos != 'absolute') {
                st.style.position = 'absolute';
                st.style.top = topPos + 'px';//this line was changed
                updatedPos = 'absolute';
                //alert('Switched to absolute');
            } else if (pos >= topPos && updatedPos != 'fixed') {
                st.style.position = 'fixed';
                st.style.top = '0';    
                updatedPos = 'fixed';
                //alert('Switched to fixed');
            }
        }
    }
    navPos();
    

    The interpreter died somewhere here:

    if (!topNavPos) {
        topNavPos = 120;
    }
    

    ​ Updated JSFiddle with the necessary changes.

    0 讨论(0)
提交回复
热议问题