使用jQuery向下滚动到某个位置

Ger*_*los 2 jquery scrolltop

嗨,我很快就怀疑这让我很生气.

单击此按钮时,我正在尝试自动向下滚动到按钮.

我已经将我的按钮的y-index值保存在名为scrollIndex的变量上(多亏了offset()方法).

现在我想用这个向下滚动窗口:

var scrollIndex = $('#tourbutton').offset();
$("body").animate({scrollTop:(scrollIndex.top)},500,"linear");
Run Code Online (Sandbox Code Playgroud)

我实际上已经尝试了很多东西,但似乎没有任何工作可以解决它,因为我正在错误地使用scrollTop方法()..

有帮助吗?谢谢!

我的完整代码:

window.onload = initAll; 

function initAll() { 
    changeStyle(); 
    $('#tourbutton').click = hello(); 
} 

function hello() { 
    var scrollIndex = $('#tourbutton').offset(); 
    $("html, body").animate({scrollTop:(scrollIndex.top)},800,"swing"); 
    //var scrollIndex = $('#tourbutton').offset();     
    //$("window").scrollTo({top:scrollIndex},800); 
}
Run Code Online (Sandbox Code Playgroud)

解决了!我只是在click()里面写了所有内容,如下所示:

function initAll() {
$('#tourbutton').click(function() {

var scrollIndex = $('#tourbutton').offset();
$("html, body").animate({scrollTop:(scrollIndex.top)},800,"swing");

//var scrollIndex = $('#tourbutton').offset();
//$("window").scrollTo({top:scrollIndex},800);
});

    changeStyle();
}
Run Code Online (Sandbox Code Playgroud)

现在一切正常,但我不太明白为什么......如果有人理解为什么我无法将click eventHandler链接到外部函数,我会很高兴知道答案.

谢谢大家!

mrt*_*man 5

你在Chrome测试吗?我遇到了另一个问题,如果你在Chrome中指定了100%的身高,那么设置滚动位置就不起作用了.您必须将站点的主体放在可滚动的div中,或者不指定100%的高度.

试试这个:

var scrollIndex = $('#tourbutton').offset();
$("html, body").animate({scrollTop:(scrollIndex.top)},500,"linear");
Run Code Online (Sandbox Code Playgroud)