2013-03-28 58 views
1

我在頁面上做了一個平滑滾動,但是當滾動到頁面上的最後一個錨點時,滾動從根本上碰撞到底部,因爲我最後的內容div不足以填充整個頁面,所以很好的緩動消失了。jQuery滾動到錨點 - >但是防止碰到頁面底部

該函數試圖將錨點放在頁面的頂部,但div是簡短的。

有什麼方法可以防止這種情況發生?有什麼方法可以告訴函數不會碰到底部?

很多人提前感謝!

http://jsfiddle.net/5FwcT/4/

$('.submenu a').bind('click',function(event){ 
var $anchor = $(this); 

$('html, body').stop().animate({ 
scrollTop: $($anchor.attr('href')).offset().top-1}, 1000,'easeInOutExpo'); 

event.preventDefault(); 


}); 

實施例這裏:

enter image description here

+0

你可以使這的jsfiddle演示?可能更容易在這裏看到問題。通常跳躍是用'event.preventDefault();'固定的,但我懷疑這裏可能不是這樣 – Ohgodwhy 2013-03-28 11:04:11

回答

1

相比提供的的jsfiddle例如當這裏的片段是不完整的。

不過,我想試試這個:

$('.submenu a').bind('click',function(event){ 
    var $anchor = $($(this).attr('href')); 
    event.preventDefault(); 
    $('html, body').stop().animate({ 
     scrollTop: $anchor.offset().top-1}, 1000,'easeInOutExpo'); 
    }); 
}); 

如果沒有更多的滾動做,瀏覽器對scrollTop將完成其工作,直到此刻也沒有更多的滾動,可因爲文件來完成結束了。沒有更多的滾動可以完成,因此如果內容高度(可能是您在此處滾動document.body)與window.innerHeight相比太小,則滾動條會非常小,並且滾動條將不足以將元素放置在視口的最上方。

我有類似的一個固定的側邊欄子導航。在這裏看到:

$(".side-nav li a").click(function(e){ 
    e.preventDefault(); 
    var target = $($(this).attr("href")); 
    $("body").animate({ 
     scrollTop: target.offset().top - 50 
    },1500); 
}); 

這是因爲我使用的是固定的導航欄在頁面的最頂端將滾動目標進入視野,頂部的餘量。當它即將滾動到視野外時,我也將該子導航固定到位(css :: position:fixed)。

1

你可以嘗試這樣的事:

Working Example

$(function() { 
    $('.submenu a').bind('click', function (event) { 
     var $anchor = $(this); 
     if ($anchor.attr('href') != "#webservers") { // if href does not = #webservers 
      $('html, body').animate({ // animate as usual 
       scrollTop: $($anchor.attr('href')).offset().top - 1 
      }, 3000, 'easeInOutExpo'); 
     } 
     if ($anchor.attr('href') == "#webservers") { // if href does = #webservers 
      $('html, body').animate({ 
       scrollTop: $('body').height() - $(window).height() // animate to the body's height minus the window's height, basically the bottom of the page less the height of the window. 
      }, 3000, 'easeInOutExpo'); 
     } 
     event.preventDefault(); 
    }); 
}); 
+0

美麗。非常感謝你!我會盡快(4小時內)獎勵賞金。 – riseagainst 2013-08-31 14:58:30

+0

保羅,一個問題。這對我來說無論如何,我也不知道使用的插件,如此偉大的東西,謝謝。但是,假設最後一個錨點下面有更多內容,僅僅不足以填滿整個頁面,是否有辦法讓它滾動到最大值,而不會像第一個問題那樣「碰到」頁面底部?謝謝。 – riseagainst 2013-09-03 14:34:51

+0

@guisasso是這樣的:http://jsfiddle.net/5FwcT/8/? – apaul 2013-09-03 15:36:18