2011-08-12 114 views
1

所以我使用下面的腳本來平滑地滾動命名的錨點,但當目標位於頁面中的錨點上方時(不會向上滾動),它不起作用。Jquery scroll up up

$(document).ready(function(){ 
     $('a[href^="#"]:not(.top)').click(function(event){ 
     event.preventDefault(); 
    var full_url = this.href; 
     var parts = full_url.split("#"); 
     var trgt = parts[1]; 
     var target_offset = $("#"+trgt).offset(); 
     var target_top = target_offset.top; 
     $('html, body').animate({scrollTop:target_top}, 500); 
    }); 
}); 

有誰知道如何讓它友好?

編輯:

我目前使用這種向上現在滾動,但如果你知道一個更清潔的方式做到這一點的一個功能,請張貼遠:

$('.top').click(function(event){ 
    event.preventDefault(); 
    $('html, body').animate({scrollTop:0}, 500); 
}); 

回答

3

這對我的作品,使用元素ID而不是命名錨點。

無論如何,您應該使用ID而不是命名錨 - 命名錨在HTML5中已棄用。那就是:

<a name="section1"><h1>Section One</h1></a> 

should be: 

<h1 id="section1">Section One</h1> 

而且你可以在一個功能相結合的滾動:

$('a[href^="#"]').live('click',function(event){ 
    event.preventDefault(); 
    var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0; 
    $('html, body').animate({scrollTop:target_offset}, 500); 
}); 
+1

由於沒有意識到他們被棄用或散列錨可以去標識醚。 –

+1

我更新了腳本,你應該能夠消除.top類現在 –

+0

再次感謝一個魅力 –