【问题标题】:Sleep function before smooth scroll平滑滚动前的休眠功能
【发布时间】:2015-02-14 13:40:59
【问题描述】:

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

【问题讨论】:

  • 请在您的帖子中使用代码块,而不是引用块作为示例代码。谢谢
  • @IsabelHM 已编辑,谢谢!
  • setTimeout(function() { ...your animate code here... }, 3000);
  • @LawrenceCherone 非常感谢!

标签: javascript jquery scroll smooth-scrolling


【解决方案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;
      }
    }
  });
});

【讨论】:

  • 非常感谢!很亲切
【解决方案2】:

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

【讨论】:

  • 非常感谢您的友好回答
猜你喜欢
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多