平滑滚动前的睡眠功能

Sleep function before smooth scroll

本文关键字:功能 滚动 平滑      更新时间:2023-10-25

如何在平滑滚动之前添加3秒的暂停?用户将点击按钮,然后会有3秒的睡眠,然后会运行平滑滚动。

 $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

您可以添加一个setTimeout(),如下所示:

 $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        setTimeout(function(){
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000);
        }, 3000);
        return false;
      }
    }
  });
});

您可以使用JavaScript标准的setTimeout()函数:

JavaScript

setTimeout(function () {
    // function that is executed after the timer ends
}, 3000);

正如您所看到的,setTimeout函数有两个参数:一个是将在计时器结束后执行的处理程序(函数),另一个是以毫秒为单位定义计时器持续时间的整数。

如果您不熟悉所有这些"处理"概念,请考虑下面的例子,我们也这样做,但首先将函数"保存"在变量中

JavaScript

var fnCallback = function () {
    console.log('This plague works.');
};
// Call setTimeout() with a handler function (fnCallback), and an integer (3000)
setTimeout(fnCallback, 3000);