平滑滚动前的睡眠功能

时间:2015-02-14 13:41:00

标签: javascript jquery scroll smooth-scrolling

如何在平滑滚动之前添加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;
      }
    }
  });
});

2 个答案:

答案 0 :(得分:1)

你可以这样添加一个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;
      }
    }
  });
});

答案 1 :(得分:0)

您可以使用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);