简体   繁体   中英

Scrolling to an anchor after an interval

I am using the below code to auto scroll to an id after a duration.

setTimeout( function() {
   $('html, body').animate({
     'scrollTop': $('#about').offset().top
   }, 2000);
}, 3000);

However I have seen so many different ways to achieve this simple task.

It's probably too objective to ask what the best way to do this is, but I need to know if I am doing something wrong with this code. Seems to work fine in current versions of Chrome, FF and IE

Thanks in advance!

For animation you should use delay and no need to use quotes around single string object key:

   $('html, body').delay(3000).animate({
     scrollTop: $('#about').offset().top
   }, 2000);

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

To answer your question, no you are not doing something wrong.

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