How to resize navbar logo on scroll down

前端 未结 4 983
伪装坚强ぢ
伪装坚强ぢ 2020-12-28 10:56

So I have this navbar with a logo on it. I would like the logo to be big when the user is in the header section of the page, but then shrink when the user scrolls down. Any

4条回答
  •  梦毁少年i
    2020-12-28 11:40

    Bare in mind that the suggested solutions so far will apply the css on every single scroll event (literally hundreds or even thousands of times), decreasing scrolling smoothness/performance.

    I've made a little addition to the solution from Robin Wright which you can find a fiddle of here to test it. This ensures that the css is only applied when you cross the border of the header (in this case 150px).

    The code is the following:

    window.onscroll = function() {
      growShrinkLogo()
    };
    
    var Logo = document.getElementById("Logo");
    var endOfDocumentTop = 150;
    var size = 0;
    
    function growShrinkLogo() {
    var scroll = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
    
      if (size == 0 && scroll > endOfDocumentTop) {
        Logo.style.width = '30px';
        size = 1;
      } else if(size == 1 && scroll <= endOfDocumentTop){
        Logo.style.width = '60px';
       size = 0;
      }
    }
    

    PS. in the fiddle i've also added a transition for the logo.

提交回复
热议问题