2017-02-01 5 views
0

WordPressで「アニメート」と「スクロールトップ」を使用して外部ページから作業するアンカーリンクを作成しようとしていますが、アンカーを使用して特定のIDに移動しようとすると最初のリンクだけを除いて、アンカーidの代わりにページを下にスクロールし、想定どおりに動作します。jQueryを使用して異なるページからWordPressにスクロール

 function foo(){ 
     $('#masthead #site-navigation a[href*="#"]:not([href="#"])').click(function() { 

     // top offstet 
     var offset = 10; 
     // get target form hash 
     var target = $(this.hash); 
     // Get hash from this 
     var hash = $(this).attr('href'); 
     // Get URL from injected JavaScript page object siteInfo 
     var host = siteInfo.siteUrl; 

     // if home 
     if($('body.home').length > 0){ 

      target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 

      if (target.length) { 
      $('html, body').animate({ 
       scrollTop: target.offset().top + offset 
      }, 1000); 
      return false; 
     } 
     } 
     else { 
     window.location = host+"/#"+hash.substring(1); 
     return false; 
     } 
    }); 
    } 

foo(); 

答えて

1

あなたの目標は、あなたが以下の持っているどのような有効なDOM要素 がtarget

target = "/#"+hash.substring(1); 

あなたはその

target = $('#'+hash.substring(1)); 

ターゲットは、今となっとともに、jQueryのセレクタを必要とする文字列を作ることがあります.offset().topが有効なdom要素で、

の値を返します。

PSページがリロードされる場合は、JSスクリプト自体は再びすべての上

$('#masthead #site-navigation a[href*="#"]:not([href="#"])').click(function() { 
    var offset = 10; // <-- change the value here 
    // Get hash from this 
    var hash = $(this).attr('href'); 
    // Get URL from injected JavaScript page object siteInfo 
    var host = siteInfo.siteUrl; 
    window.location = host+"/#"+hash.substring(1); 
}); 

をロードされますので、その後、.animate()はあなたがターゲットのみのJSに以下のセクションを必要とする.click()関数の外である必要がありますページ。これは、現在のURLを取得し、あなたは私が外にクリック機能をアニメーションに置くべきか

var currentUrl = window.location.href; 
if(currentUrl.includes('#')) { 
    var urlArray = currentUrl.split('#'); 
    // gets the dom that has the id evaluated from `hash.substring(1)` 
    target = $('#'+urlArray[1]); 
    $('html, body').animate({ 
    scrollTop: target.offset().top + offset 
    }, 1000); 
} 
+0

をスクロールしているdiv要素のIDに対応している必要があり#後にテキストを取得しますか?コールバックかもしれない? – Darko

+0

また、 "target.offset(...)が定義されていません"というエラーが表示される – Darko

+0

リンク先の同じページでスクロールしたいdiv/sectionですか()? –

関連する問題