Home  >  Q&A  >  body text

javascript - A small question about scroll event

window.addEventListener('scroll',()=>{
        let t = document.documentElement.scrollTop || document.body.scrollTop,
        nav = document.getElementsByClassName('nav')[0];
        t >= nav.offsetTop ? (nav.classList.add('fixed')) : (nav.classList.remove('fixed'));
})

Hello everyone, the above code cannot remove the class name add normally. . . Even if I reverse the order of add and remove, I still can't execute it;
I have been searching for this problem for a long time but cannot solve it, so I would like to ask for your advice. Thank you thank you.

phpcn_u1582phpcn_u15822634 days ago676

reply all(2)I'll reply

  • 仅有的幸福

    仅有的幸福2017-07-05 11:02:30

    nav.offsetTop is 0 right.

    Change t >= nav.offsetTop to t > nav.offsetTop.

    reply
    0
  • 天蓬老师

    天蓬老师2017-07-05 11:02:30

    1. First, take a look at the output of t and nav.offsetTo to make sure these values ​​are the expected values

    2. Make sure your scrolling area is on the body and not on a certain p in the body

    reply
    0
  • Cancelreply