2012-01-30 57 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