使用JavaScript实现平滑的自动滚动

22

我正在尝试在我的网页上实现自动滚动的功能。我使用了一个JavaScript函数来执行自动滚动,并在页面加载时调用了该函数,但页面仍然无法平稳滚动!有没有办法使页面平稳地自动滚动?

以下是我的JavaScript函数:

function pageScroll() {
        window.scrollBy(0,50); // horizontal and vertical scroll increments
        scrolldelay = setTimeout('pageScroll()',100); // scrolls every 100 milliseconds
}
9个回答

48

由于您每100毫秒滚动增加50,因此滚动不够平滑。

将滚动量和滚动增量调小,可以让函数看起来更加“流畅”。

调整速度以使其更快或更慢。

function pageScroll() {
    window.scrollBy(0,1);
    scrolldelay = setTimeout(pageScroll,10);
}

看起来会更加流畅,试试吧 ;)


1
你能告诉我在这段代码中有什么方法可以让用户使用鼠标滚动时停止自动滚动吗? - hiteshtr
1
我建议不要将字符串传递给 setTimeout,因为这相当于调用 eval('pageScroll')。可以使用以下代码:setTimeout(function(){ //酷炫的代码在这里 }, 10)在这里,您将一个函数传递给 setTimeout,而不是一个字符串。 - johnnyutah
@johnnyutah 后者才是目的。这似乎是我自己的笔误,抱歉。 - Michael Zaporozhets
这个例子会导致堆栈溢出,你可能想要移除pageScroll函数的调用,并直接将它传递给setTimeout而不是调用它。 - akst
1
scrollBy支持一个“behavior”字典,可以将滚动设置为“smooth”或“auto”:https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior - user136036
显示剩余3条评论

13

试着使用jQuery,使用以下代码:

$(document).ready(function(){
     $('body,html').animate({scrollTop: 156}, 800); 
});

156 - 位置滚动到(像素),从页面顶部开始。
800 - 滚动持续时间(毫秒)


2
只是一个更正,800是动画的持续时间,而不是速度。 - Dogoku

1

流畅运行的动画取决于客户端的设备。无论你编写代码多么公平,你永远不会满意在128 MB内存系统上运行动画的方式。

以下是使用jQuery进行滚动的方法:

$(document).scrollTop("50");

你可能还想尝试一下AutoScroll插件


1

jfunc.com 域名出售 - alancalvitti

1

你可能想查看jQuery ScrollTo插件的源代码,它可以平滑地滚动。或者干脆使用该插件而不是自己编写函数。


0
这里有另一种方法,使用requestAnimationFrame。它可以让你控制滚动时间,并支持缓动函数。它非常强大,但需要注意的是:用户无法中断滚动。
// Easing function takes an number in range [0...1]
// and returns an eased number in that same range.
// See https://easings.net/ for more.
function easeInOutSine(x) { return -(Math.cos(Math.PI * x) - 1) / 2; }

// Simply scrolls the element from the top to the bottom.
// `elem` is the element to scroll
// `time` is the time in milliseconds to take.
// `easing` is an optional easing function.
function scrollToBottom(elem, time, easing)
{
  var startTime = null;
  var startScroll = elem.scrollTop;
  // You can change the following to scroll to a different position.
  var targetScroll = elem.scrollHeight - elem.clientHeight;
  var scrollDist = targetScroll - startScroll;
  
  easing = easing || (x => x);
  function scrollFunc(t)
  {
    if (startTime === null) startTime = t;
    
    var frac = (t - startTime) / time;
    if (frac > 1) frac = 1;
    
    elem.scrollTop = startScroll + Math.ceil(scrollDist * easing(frac));
    
    if (frac < 0.99999)
      requestAnimationFrame(scrollFunc);
  }
  requestAnimationFrame(scrollFunc);
}

// Do the scroll
scrollToBottom(document.getElementById("data"), 10000, easeInOutSine);

0

既然您将问题标记为“jquery”,为什么不尝试使用.animate()之类的东西呢?这个特定的jquery函数被设计用于平滑地动画化各种属性,包括数字CSS属性以及滚动位置。


也许他的意思是解决方案可以用jQuery或纯JS编写。 - Fabián

0

这些数字是硬编码的,但思路是逐个移动项目(标题高度为52像素),当到达底部时返回。

let elem = document.querySelector(".spfxBirthdaysSpSearch_c7d8290b ");
let lastScrollValue = 0
let double_lastScrollValue = 0
let scrollOptions = { top: 79, left: 0, behavior: 'smooth' }
let l = console.log.bind(console)

let intScroll = window.setInterval(function() {
    double_lastScrollValue = lastScrollValue //last
    lastScrollValue = elem.scrollTop // after a scroll, this is current
    if (double_lastScrollValue > 0 && double_lastScrollValue == lastScrollValue){
        elem.scrollBy({ top: elem.scrollHeight * -1, left: 0, behavior: 'smooth' });
    } else {
        if (elem.scrollTop == 0){
            elem.scrollBy({ top: 52, left: 0, behavior: 'smooth' });
        } else {
            elem.scrollBy(scrollOptions);
        }
    }
}, 1000);

0
使用这个函数来实现平滑滚动到底部。
$(document).ready(function(){
  const scrollingElement = (document.scrollingElement || document.body);

  const scrollSmoothToBottom = () => {
  $(scrollingElement).animate({
  scrollTop: document.body.scrollHeight,
  }, 500);
 }
 scrollSmoothToBottom();
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接