2

嗨,只是一个让我发疯的快速怀疑。

单击此按钮时,我试图自动向下滚动到一个按钮。

我将按钮的 y 索引值保存在一个名为 scrollIndex 的变量中(感谢 offset() 方法)。

现在我试图用这个向下滚动我的窗口:

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

我实际上尝试了很多东西,但似乎没有任何效果,我想这是因为我错误地使用了 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); 
}

解决了!我只是像这样在 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();
}

现在一切正常,除了我不太明白为什么......如果有人明白为什么我不能将点击事件处理程序链接到外部函数,我会很高兴知道答案。

谢谢大家!

4

1 回答 1

5

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

试试这个:

var scrollIndex = $('#tourbutton').offset();
$("html, body").animate({scrollTop:(scrollIndex.top)},500,"linear");
于 2012-01-30T15:23:24.823 回答