仅javascript平滑滚动按钮按下

Javascript-only smooth scroll on button press

本文关键字:按钮 滚动 javascript 平滑      更新时间:2023-09-26

这个网站有一个全高的图像开始。进一步的内容位于折叠下方,在图像底部有一个"滚动"元素,提示用户发现其余的内容。点击后,我成功地将网站向下滚动了300像素。不过,我想让这一切顺利进行。下面是我当前的代码:

  window.onload = function () { 
    var scroll = document.getElementById("scroll");
    scroll.onclick = function () {
        var top = self.pageYOffset; 
        var goal = 300; 
        for(var i=0, l=goal; i<l; ++i) {
        window.scrollBy(0,1);
        }       
   }; 
};

这适用于滚动,但不流畅。我想如果我有for循环,改变窗口。scrollBy值设置为。001之类的值会使滚动更慢(因此,平滑),但该函数似乎不接受小数点。

提示吗?从技术上讲,现在已经没问题了,但我想再加最后一点润色。谢谢!

您的代码运行得非常快,您看不到平滑的效果。您必须使用setInterval()函数,并在每次迭代(n -迭代次数)中滚动到300/n px。这样的:

window.onload = function () { 
    var scroll = document.getElementById("scroll");
    scroll.onclick = function () {
        var currentScroll = 0; 
        var goal = 300;
        var step = goal/10
        var timer = setInterval( function () {
            if (currentScroll < goal) {
                window.scrollBy(0, step);
                currentScroll += step;
            } else {
                clearInterval(timer);
            }
        }, 50);
    };
};       

试试这样做…example

 $(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;
          }
        }
      });
    });