开发者

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 le开发者_如何学Goss 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜