2012-06-05 106 views
2

我有一個網站,使用頁面頂部的固定菜單。jQuery scrollTo - 在垂直窗口的中心Div

當單擊一個鏈接時,它應該垂直滾動,以便該目標div的中心與窗口的垂直中心對齊,並由標題的高度偏移。 - 這是非常重要的,所以無論顯示器的分辨率爲何div都居中

我正在使用jQuery和scrollTo,但無法弄清楚爲此需要的數學。

這裏是我的嘗試:

function scrollTo(target) { 
var offset; 
var scrollSpeed = 600; 

if (viewport()["width"] > 767 && !jQuery.browser.mobile) { 
    // Offset anchor location and offset navigation bar if navigation is fixed 
    offset = $(target).offset().top - document.getElementById('navigation').clientHeight; 
} else { 
    // Offset anchor location only since navigation bar is now static 
    offset = $(target).offset().top; 
} 

    $('html, body').animate({scrollTop:offset}, scrollSpeed); 
} 
+0

我*想*你應該將滾動的div對齊到窗口的頂部,以防你有一個高度大於瀏覽器窗口的div,它的頂部不會被截斷。除非你確定所有div都<= 400px。 –

+0

如果您可以在http://jsfiddle.net上發佈您的標記的實時演示以進行測試,那將會很不錯。 –

回答

0

最終弄明白了。對數學只是啞巴。使用固定頁眉和頁腳進行偏移,適用於所有分辨率。

// scrollTo: Smooth scrolls to target id 
function scrollTo(target) { 
    var offset; 
    var scrollSpeed = 600; 
     var wheight = $(window).height(); 
     //var targetname = target; 
     //var windowheight = $(window).height(); 
     //var pagecenterH = windowheight/2; 
     //var targetheight = document.getElementById(targetname).offsetHeight; 

    if (viewport()["width"] > 767 && !jQuery.browser.mobile) { 
     // Offset anchor location and offset navigation bar if navigation is fixed 
     //offset = $(target).offset().top - document.getElementById('navigation').clientHeight; 
       offset = $(target).offset().top - $(window).height()/2 + document.getElementById('navigation').clientHeight + document.getElementById('footer').clientHeight; 
    } else { 
     // Offset anchor location only since navigation bar is now static 
     offset = $(target).offset().top; 
    } 

    $('html, body').animate({scrollTop:offset}, scrollSpeed); 
} 
-1

我做了一個簡單的jQuery。我認爲這可能有助於你在尋找什麼。

請參閱demo

目標div留垂​​直居中offset頭。

+0

這改變了div的邊距,我需要實際滾動到div,因爲頁面包含衆多的div。 – jwg2s