2017-08-31 168 views
0

我有一個導航欄,鏈接到首頁上的不同錨點。當我在首頁使用導航中的鏈接時,它會平滑地滾動到正確的ID。但是當我去到一個子頁面/其他頁面時,我想讓導航欄直接發回我的首頁和選擇的ID(錨點)。我認爲與平滑滾動JavaScript有一些衝突,但我可能是錯的。從WP導航到不同頁面的鏈接錨點

我的自定義WP主題的名字是:fitnesstravels。

導航欄是由從WordPress的菜單前自定義鏈接:

網址:http://localhost:8080/fitnesstravels/#destinations

名稱:目的地

,當我去喜歡一個子頁面:http://localhost:8080/fitnesstravels/destinations/rhodos

的菜單 - 鏈接在我的導航欄名爲「目的地」鏈接到http://localhost:8080/fitnesstravels/#destinations錨點(如果我右鍵點擊「打開鏈接在新標籤」我得到發送到正確的地方。菜單鏈接。

的JS:

$('.nav.navbar-nav a, .arrow a[href^="#"]').on('click',function (e) { 
    e.preventDefault(); 
    var target = this.hash, 
    $target = $(target); 
    $('html, body').stop().animate({ 
      'scrollTop': $target.offset().top-50 
    }, 1200, 'swing', function() { 
      window.location.hash = target; 
    }); 
}); 
+2

我真的是你想要什麼來實現或有什麼問題不明白.. – Stephen

+0

的問題是,我的導航不要送我回我的FrontPage和正確的#anchor當IM子頁面。當我點擊菜單/導航欄中的鏈接時,沒有任何反應。但如果我在我的首頁上導航工作,並滾動到正確的錨分區。 – csk87

+1

好吧,你可以只針對鏈接與哈希在他們中,就像這樣 $('。nav.navbar-nav a [href * =「#」]')。on(...); – Stephen

回答

0

的問題是e.preventDefault()

我已經完成了你想要在網站上做的事情,就像你描述的一樣,唯一明顯的區別是我的平滑滾動jQuery沒有使用preventDefault

這是(相關部分)我的平滑滾動的jQuery:

var $root = $('html, body'); 

$(".navbar").on("click", "li a", function() { 
    var pageanchor = this.hash; 
    if (pageanchor) 
     $root.animate({ scrollTop: $(pageanchor).offset().top}, 500); 
}); 

如果我改變我的代碼使用變量名和動畫設置,它是除了preventDefault幾乎等同於你的。

$(document).ready(function() { 
    $('.nav.navbar-nav a, .arrow a[href^="#"]').on('click',function (e) { 
     var target = this.hash; 
     if (target) 
      $('html, body').animate({ 
       scrollTop: $(target).offset().top-50 
      }, 1200, 'swing', function() { 
       window.location.hash = target; 
     }); 
}); 
+0

是的,我打了preventDefault是問題。但問題仍然存在,即使我從我的js中刪除'e.preventDefault();'。 菜單鏈接將無法正常工作,除非我在我的主頁上。 – csk87

+1

猜猜我的瀏覽器沒有更新scroll.js足夠快:P現在它就像一個魅力! thx @FluffyKitten – csk87