javascript - html/js中没有点击功能的滚动页面 Action

标签 javascript jquery html scroll

我使用此代码在单击按钮后滚动页面:

$(document).ready(function() {
  $("#button").click(function(e) {
    e.preventDefault();
    $('html, body').animate({
      scrollTop: $($.attr(this, 'href')).offset().top
    }, 8000);
  });
});

但我想让它在不单击任何按钮的情况下工作。当页面加载时,它应该滚动。我使用了这段代码,但它不起作用:

$(document).ready(function() {
  $('html, body').animate({
    scrollTop: $($.attr(this, 'href')).offset().top
  }, 8000);
});

最佳答案

我个人不太喜欢使用 jQuery 的 animate 函数,所以我实现了自己的。您可以通过增加或减少 setTimeout 函数的时间来改变它的速度。

$(document).ready(function() {
    var pixels = $('a').position();
    Scroll(pixels.top);
});

function Scroll(pixels) {
    if( pixels > 0){
        window.scrollBy(0,1);
        scrollTimeout = setTimeout(function(){
            Scroll(pixels-1); 
        },1);
    }
    else {
        clearTimeout(scrollTimeout)
        return;
    }
}

这是我制作的 fiddle 链接,用于演示我认为您正在尝试做的事情。 如果这有帮助请告诉我!

https://jsfiddle.net/ogb4t33q/

关于javascript - html/js中没有点击功能的滚动页面 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35152007/

相关文章:

javascript - chrome 中的 bootstrap js 文件未为 wordpress 加载

javascript - Ramdajs keyBy 相当于lodash

javascript - 在计算JavaScript中绘制数组的正确算法时遇到麻烦

javascript - 在 Jestjs 中替代 spyOn().and.callfake

jquery - 在 Slick Slider 中显示下一张幻灯片的一半,无需居中模式

jquery - 具有相对位置句柄显示/隐藏的水平滑动面板 - jQuery

html - Bootstrap 导航栏图标未正确对齐

html - 标题/导航问题

html - 即使窗口调整大小时,也让文本在左浮动和右浮动 div 之间居中?

javascript函数-在引号内使用参数?