简体   繁体   中英

Animate scroll to a div with an ID

I know this has probably been asked before but I couldn't find the right answer.

I'm trying to have a link, when you click it, scrolls the page to an element with an ID, with just javascript, and I get to control the speed.

I know about:

document.getElementById('youridhere').scrollIntoView();

and that didn't work. It just snapped into view. I also tried scrollBy but that didn't work since it works in increments. I can write it up to check the remaining distance to the element and if it's less than the increment, then only move what's left, but that seems way too bulky.

I tried scrollTo as well but that wasn't helping much either.

Is there a cleaner way of doing this?

This needs to be javascript only. Here is a jquery equivalent:

var top = target.offset().top;

$('html,body').animate({scrollTop: top}, 1000);

There is no built-in way to smooth scroll. I would use setInterval and scrollBy an increment on each iteration, then clearInterval when done.

You could also check the jQuery source to see how they do it.

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