简体   繁体   中英

How to make an element smooth scrollable

I have a container element with a height of 500px. The content inside the <div> overflows so that I can make it scrollable. I have overflow hidden applied to the container element so that I can transition the value of the y-axis to make it look like smooth scrolling. But I can't seem to figure out how to hijack the window scroll event for that particular container element and translate the Y-axis.

<div class="container" style="height: 500px; overflow: hidden;">
     <div class="content" style="min-height: 1000px;"></div>
</div>

I am looking for a way to make the custom scrolling ease. Kind of like what a popular scroll library like a locomotive does. Here is an example website https://www.white-elephant.fr/ . This website use locomotive for their smooth scrolling effect.

I am already able to create a custom scrollbar and bind it to the translateY value of the container, but the difficulty I am having is I don't have any idea on how to bind mousewheel event to the container.

You can use the property in your css or add style:

scroll-behaviour: smooth

but this doesn't work in internet explorer. Majority of browser it will work.

Add scroll-behavior property to the container class:

.container {
   scroll-behavior: smooth;
}

I created a smooth scroll libary thats pretty easy to use without any dependencies.
ScrollToSmooth can apply smooth scrolling animations to any element or position on your page with 31 predefined easing animations.

It's tree shakable which means you do not need to bundle it with all animations at once.

Just npm install scrolltosmooth and

import { 
  scrollToSmooth, 
  easeOutCubic 
} from 'scrolltosmooth';

let smoothScroll = new scrollToSmooth('a', {
  easing: easeOutCubic
});
smoothScroll.init();

Don't hide the overflow, just hide the scrollbar...

    div.content {
        overflow: scroll;
        scroll-behavior: smooth;
    }
    div.content::-webkit-scrollbar {
        width: 0;
    }

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