2013-08-19 23 views
1

所以我得到了jQuery滾動工作在我的頁面上很好。 但我想改變一件事。 我不想在url中顯示錨文本。即。 #products或#contactinfojQuery滾動:防止錨文本出現在url中

HTML代碼:

<div> 
<a href="#products">Products</a> 
<a href="#contactinfo">Contact info</a> 
</div> 

<div id="products"></div> 

<div id="contactinfo"></div> 

jQuery代碼:

$(document).ready(function(){ 
    $('a[href^="#"]').on('click',function (e) { 
     e.preventDefault(); 

     var target = this.hash, 
     $target = $(target); 

     $('html, body').stop().animate({ 
      'scrollTop': $target.offset().top 
     }, 900, 'swing', function() { 
      window.location.hash = target; 
     }); 
    }); 
}); 
+0

長鏡頭,但你試過將其更改爲$('一[href^=「#」]')? – LorDex

回答

5

試試這個:

HTML:

<div> 
    <span class="link" rel="#products">Products</span> 
    <span class="link" rel="#contactinfo">Contact info</span> 
</div> 

<div style="height:800px;"></div> 
<div id="products">products</div> 
<div style="height:800px;"></div> 
<div id="contactinfo">contact</div> 
<div style="height:800px;"></div> 

腳本:

$(document).ready(function(){ 
    $('.link').on('click',function (e) { 
     $('html, body').stop().animate({ 
      'scrollTop': $($(this).attr('rel')).offset().top 
     }, 900, 'swing', function() {}); 
    }); 
}); 

Fiddle

1

只是在click函數的末尾添加一個return false;。 編輯:和probalby刪除這條線,我的意思是..它確實是你不想要的? Appearently?

window.location.hash = target; 
+0

不起作用。 http://jsfiddle.net/KxAQL/1/ – Pietu1998

+0

對我來說它工作,但無法測試散列網址,雖然它的iframe – Alex

+0

它確實工作,在網址沒有哈希:http://jsfiddle.net/KxAQL/6/ – Alex