Javascript fixed-top navbar only after scrolling

2019-03-21 15:20发布

问题:

Does anyone know what javascript effects are being used to create the navbar effect on lesscss.org where the navbar only becomes fixed to the top after scrolling beyond a certain point. If anyone has actual code examples, or links to tutorials, that'd be appreciated.

回答1:

it's a javascript check using the window.onscroll event

in the HTML source near the top:

window.onscroll = function () {
    if (!docked && (menu.offsetTop - scrollTop() < 0)) {
      menu.style.top = 0;
      menu.style.position = 'fixed';
      menu.className = 'docked';
      docked = true;
    } else if (docked && scrollTop() <= init) {
      menu.style.position = 'absolute';
      menu.style.top = init + 'px';
      menu.className = menu.className.replace('docked', '');
      docked = false;
    }
};