简体   繁体   中英

Hide scrollbar when not scrolling (Mac like behaviour)

My Vue web app on Mac browsers shows very elegant scrollbar. But same App on Windows, breaks the UI as the width is too much and the scroll is always visible.

Too solve this issue I created scroll bar from CSS and added event listener to show scrollbar only when it starts to scroll.

div * {
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE 10+ */
    ::-webkit-scrollbar-track {
        -webkit-box-shadow: none !important;
        background-color: transparent;
    }
    ::-webkit-scrollbar {
        width: 3px !important;
        background-color: transparent;
    }
    ::-webkit-scrollbar-thumb {
        background-color: transparent;
    }
}
.on-scrollbar{
    scrollbar-width: thin; /* Firefox */
    -ms-overflow-style: none; /* IE 10+ */

  }
  
  .on-scrollbar::-webkit-scrollbar-track {
    -webkit-box-shadow: none !important;
    background-color: transparent !important;
  }
  
  .on-scrollbar::-webkit-scrollbar {
    width: 6px !important;
    background-color: transparent;
  }
  
  .on-scrollbar::-webkit-scrollbar-thumb {
    background-color: #acacac;
  }

JS:

window.addEventListener('scroll', (e) => {
    if (e.target.classList.contains("on-scrollbar") === false) {
        e.target.classList.add("on-scrollbar");
    }
}, true);

But the issue is, once the scroll bar is visible. I am not able to remove/hide the scrollbar when not scrolling. Basically I am trying to implement the default behaviour of scrollbar that we have on Mac. Can anyone help me on this?

Hopefully this helps. A bit of debouncing and css for scrollbar. If you want to change the style / animation of changing width, there are better resources for that. Good luck!

 function debounce(func, timeout = 300){ let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => { func.apply(this, args); }, timeout); }; } window.addEventListener("mousewheel", e => { document.querySelector("div").classList.remove("hidden"); }); window.addEventListener("mousewheel", debounce(e => { document.querySelector("div").classList.add("hidden"); }));
 div { background: gray; overflow: auto; height: 300px; width: 100%; } div > div { background: lighblue; height: 800px; } /* width */ .shown::-webkit-scrollbar { width: 10px; } /* width */ .hidden::-webkit-scrollbar { width: 0px; } /* Track */ ::-webkit-scrollbar-track { background: black; } /* Handle */ ::-webkit-scrollbar-thumb { background: white; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: lightblue; }
 <div class="shown"> <div></div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM