简体   繁体   中英

How can I delay a click to scroll event?

Here's what I want to achieve:

  1. Click on down arrow at the bottom of a hero container.
  2. Have keyframes animation take place. (Specifically, have contents on the div fade out and have the background change colour to match the background of the div below.)
  3. After the animation has completed, immediately scroll to the div below, after which its contents will fade in.

I'm pretty much completely new to CSS, HTML, and JS, but have managed to get steps 1&2 done.

To try to achieve step 3 I'm using the following code I found at https://stackoverflow.com/a/6677069 :

$("#top").click(function() {
$([document.documentElement, document.body]).animate({
    scrollTop: $("#bottom").offset().top
}, 3000);
});

It creates a smooth scroll for the duration set at the end (which, in the above example, is 3000ms/3 seconds).

And here it is in action:

 $("#top").click(function() { $([document.documentElement, document.body]).animate({ scrollTop: $("#bottom").offset().top }, 3000); }); 
 #stuff { text-align: center; height: 30vh; margin: 20vh 0; font-size: 5rem; } #top { cursor: pointer; text-align: center; height: 1vh; font-size: 5rem; } #star { text-align: center; font-size: 100px; line-height: 500px; color: #ddd; height: 100vh; } #bottom { text-align: center; font-size: 100px; color: green; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="stuff"> Click arrow to scroll down</div> <div id="top">˅</div> <div id="star">&star;</div> <div id="bottom">This is the bottom</div> 

What I'd like is to either modify this code or use new code that'll jump to the div (rather than smooth scroll) a set number of seconds after the click has taken place.

Please help.

You can add a delay function .delay() before the .animate() function, this will delay the animation by 3secs.

$([document.documentElement, document.body]).delay(3000).animate({
  scrollTop: $("#bottom").offset().top
}, 3000);

https://codepen.io/_kram/pen/aXXWNm

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