簡體   English   中英

鏈接到WP導航不同頁面上的錨點

[英]Link to anchor on different page from WP nav

我有一個導航欄,該導航欄鏈接到起始頁上的不同錨點。 當我使用首頁上導航中的鏈接時,它會平滑滾動到正確的ID。 但是當我轉到子頁面/其他頁面時,我希望導航欄將我直接發送回首頁和所選的ID(錨定)。 我認為平滑滾動javascript有一些沖突,但我可能是錯的。

我的自定義WP主題的名稱是:Fitnesstravels。

導航欄由Wordpress菜單ex中的自定義鏈接組成:

網址: 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;
     });
});

問題是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;
        });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM