2010-10-21 46 views
17

我有下面的滾動腳本,它滾動頁面的罰款,我的工作方式也是如此。JQuery從瀏覽器頂部滾動到偏移量?

$(function(){ 
    $('a[href*=#]').click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
     && location.hostname == this.hostname) { 
      var $target = $(this.hash); 
      $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); 
      if ($target.length) { 
       var targetOffset = $target.offset().top; 
       $('html,body').animate({scrollTop: targetOffset}, 1000); 
       return false; 
      } 
     } 
    }); 
}); 

不過,我需要它忽略上面說200像素,因爲我在頁面頂部的內容滾動背後有一個固定的頭。

這意味着當我滾動到頂部它將內容滾動到固定標題後面,所以我不能看到它,所以我需要它滾動到正下方的標題..所以要將標題的底部作爲頂部瀏覽器我想....

這可以做,因爲它會很方便嗎?

非常感謝所有幫助

+0

謝謝你問這個問題一直掙扎了一夜想了解如何完全相同的原因完成此操作! – Robert 2016-11-26 08:43:37

回答

26

會是這樣的工作?

var targetOffset = $target.offset().top - 200; 

或者抓取額外偏移量的頭元素的高度。

var targetOffset = $target.offset().top - $("element").outerHeight(true); 
1

你可以使用這樣的事情,如果在我們的代碼的條件這樣做

//check if the absolute position is below header 
if ($('#IdOfTheScrollElement').position().top >= 200){ 
//scroll 
} 
else { 
//do nothing 
} 
+0

謝謝你們的幫助。我不知道他們是否工作,因爲我無法弄清楚在哪裏把它們放在代碼中來產生效果,在霧氣情況下,我只是打破了滾動:( – Jezthomp 2010-10-22 10:12:12

0

代碼很好,你只需要在這裏刪除你的固定頭的高度,例如,如果它是200px。它會完美地工作。

$('html,body').animate({scrollTop: (targetOffset().top)-200}, 1000); 

您還可以檢查此當按鈕被點擊

$(function() { 

$('a[href*=#]:not([href=#])').click(function() { 

    // Check height of the header and padding 
    var header_height = $('.header').outerHeight(); 

從你刪除它抵消

$('html,body').animate({scrollTop: (targetOffset().top) - header_height }, 1000); 
相關問題