平滑滚动前的休眠功能

Sleep function before smooth scroll

如何在平滑滚动之前添加 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 函数有两个参数:一个将在计时器结束后执行的处理程序(函数),以及一个定义计时器持续时间(以毫秒为单位)的整数。

如果您不熟悉所有这些 "handling" 概念,请考虑下面的示例,我们在其中做同样的事情,但首先 "save" 变量中的函数 :

JavaScript

var fnCallback = function () {
    console.log('This plague works.');
};

// Call setTimeout() with a handler function (fnCallback), and an integer (3000)
setTimeout(fnCallback, 3000);