简体   繁体   中英

smooth scroll to certain element within an element with overflow set to scroll

Now I know, yes there are heaps of questions on how to smooth scroll to elements on a page yes I know I can use jquery like this..

$("#button").click(function() {
$('html, body').animate({
    scrollTop: $("#myDiv").offset().top
}, 2000);
});

and yes I know I can do this with javascript

element.scrollIntoView();

but neither of those are giving me the desired result..

Okay so... Is there an easy way to scroll to an element inside a component?

So I have a sidebar and the sidebar has its own scroll outside of the body because its component with the overflow set to scroll.. so what I want to be able to do is scroll to a certain element within that component

I have tried to do..

scrollIntoView like so..

upNext.scrollIntoView({behavior: 'smooth', block: 'start'});

but I find that I cannot get it to scroll to the right place on the element, its buggy and its extra features like behavior: 'smooth' dont have great broswer support

So my question is how can I scroll to a certain element within an element with a scroll?

You have to trigger scroll in the sidebar rather than the document or html

 $('#scroll-sidebar').click(function(){ $('sidebar').animate({ scrollTop: $("#scroll-here").offset().top }, 2000); }); 
 .container{ position: relative; display: flex; background: white; } sidebar, main{ padding: 15px; } sidebar{ width: 200px; background: red; height: 400px; overflow-x: auto; } ul > li{ display: inline-block; margin: 5px 0; } main{ flex: 1; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <sidebar> <h1>Sidebar</h1> <ul> <li>Iste, doloribus!</li> <li>Labore, animi.</li> <li>Adipisci, dolores?</li> <li>Odio, excepturi.</li> <li>Odio, aliquid!</li> <li>Numquam, officia.</li> <li>Alias, officiis!</li> <li>Tenetur, quas!</li> <li>Totam, vitae.</li> <li>Dignissimos, at?</li> </ul> <hr> <ul id="scroll-here"> <li>Iste, doloribus!</li> <li>Labore, animi.</li> <li>Adipisci, dolores?</li> <li>Odio, excepturi.</li> <li>Odio, aliquid!</li> <li>Numquam, officia.</li> <li>Alias, officiis!</li> <li>Tenetur, quas!</li> <li>Totam, vitae.</li> <li>Dignissimos, at?</li> </ul> </sidebar> <main> <h1>Main Container</h1> <button id="scroll-sidebar">Scroll Sidebar</button> </main> </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