2012-01-30 52 views
2

嗨,我只是一个疑问,这让我很生气。使用jQuery向下滚动到某个位置

我试图自动向下滚动到一个按钮,当这个按钮被点击。

我已经将我的按钮的y索引值保存在一个名为scrollIndex的变量上(由于offset()方法)。

而现在我想从我的窗口,这个滚动:

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

其实我已经尝试了很多东西,但似乎没有任何工作,我supose是因为我做了错误的使用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); 
} 

解决了!我只写了这样的内部点击(一切):

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

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

谢谢大家!

+0

尝试'$( '文件')动画({scrollTop的:(scrollIndex.top)},500, “线性”);'? – 2012-01-30 15:22:48

+0

[jQuery.ScrollTo](http://demos.flesler.com/jquery/scrollTo/) – TOUDIdel 2012-01-30 15:25:27

+0

hmm我写了这个:var scrollIndex = $('#tourbutton')。offset(); (“window”)。scrollTo({top:scrollIndex},800);我得到和错误“$(”窗口“)。scrollTo不是一个函数” – 2012-01-30 15:39:09

回答

5

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

尝试这种情况:

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

我做了你所说的,现在它可以工作,但每次我加载我的页面时都会这样做!我的完整代码是这样的: – 2012-01-30 15:36:21

+0

window.onload = initAll; 函数initAll(){ \t changeStyle(); \t $('#tourbutton')。click = hello(); } function hello(){ \t \t var scrollIndex = $('#tourbutton')。offset(); (“html,body”)。animate({scrollTop:(scrollIndex.top)},800,“swing”); \t // var scrollIndex = $('#tourbutton')。offset(); \t //$("window").scrollTo({top:scrollIndex},800); } – 2012-01-30 15:36:40