简体   繁体   English

动画滚动到带ID的div

[英]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. 我想要一个链接,当你点击它时,将页面滚动到一个带有ID的元素,只需javascript,我就可以控制速度。

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. 我也尝试过scrollBy但由于它以增量方式工作,因此无效。 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. 我也尝试过scrollTo ,但这也没什么用。

Is there a cleaner way of doing this? 这样做有更干净的方法吗?

This needs to be javascript only. 这只需要javascript。 Here is a jquery equivalent: 这是一个等价的jquery:

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. 我会在每次迭代时使用setIntervalscrollBy增量,然后在完成时使用clearInterval

You could also check the jQuery source to see how they do it. 您还可以检查jQuery源代码以了解它们是如何做到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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