2016-03-21 64 views
6

我有一個onepager網站,我使用scrollmagic加上所有必要的插件/庫(和jQuery),用於動畫,釘住,淡化過程等不同效果。由滾動位置觸發。動畫滾動腳本阻止從外部鏈接訪問本地錨位置

我還將它用於動畫滾動到頁面上的定位點(從菜單和其他本地鏈接) - 請參閱以下腳本的相應部分。

的問題是,這個腳本抑制的「跳躍」直接到anchorpoint默認行爲單擊本地連接時,顯然也當頁面從外部通過直接鏈接或書籤與錨訪問附加到URL(如http://www.example.com/index.php#part3)。儘管單擊本地鏈接時需要此行爲,但顯然會阻止瀏覽器在其他位置鏈接錨點時顯示錨點位置。

有沒有什麼辦法可以讓瀏覽器直接顯示錨定位置,當點擊上面例子中的鏈接時?

var sm_controller_1 = new ScrollMagic.Controller(); 

sm_controller_1.scrollTo(function(anchor_id) { 
     TweenMax.to(window, 2.0, { 
       scrollTo: { 
         y: anchor_id 
         autoKill: true 
       }, 
       ease: Cubic.easeInOut 
     }); 
}); 
jQuery(document).on("click", "a[href^=#]", function(e) { 
     var id = jQuery(this).attr('href'); 
     if(jQuery(id).length > 0) { 
       e.preventDefault(); 
       sm_controller_1.scrollTo(id); 
       if (window.history && window.history.pushState) { 
         history.pushState("", document.title, id); 
       } 
     } 
}); 

(由於問題在於從外部源調用原始URL,所以創建小提琴/ codepen沒有任何意義)。

回答

1

你可以嘗試使用此代碼:

jQuery(function ($) { 
    $(document).ready(function() {// if needed, use window.onload which fires after this event 
     if(window.location.hash) { 
      var hash = window.location.hash; 
      $('a[href=' + hash + ']').click(); 
     } 
    }); 
}); 

它會等到DOM(或頁)被加載,然後模擬在導航項目的用戶點擊。

當我再次閱讀您的問題後,我不再確定您是否希望將頁面加載到錨點中列出的元素的位置,或者來自外部的滾動不起作用資源?

如果條幅是工作,但你想在正確的位置來顯示頁面,就像一個跳躍,然後我提出2個解決方案:

一)使用CSS opacity:0;對身體和滾動結束後,請將其重新設置爲opacity:1; b)嘗試跳到頁面上的正確位置,然後加載ScrollMagic

+0

是的,這個工程!我只是使用了你發佈的代碼,而不是下面的建議,因爲它已經按我想要的方式工作(即當頁面加載URL中的錨點時直接跳到錨點)。非常感謝你! – Johannes

2

那麼假設滾動魔法可是沒有這裏沒有公佈額外的功能,可能會得到我的回答的方式,你可以試試這個:

數據屬性添加到您想要使用默認的行爲你的鏈接:

<a href="example.com/index.php#part3.php" data-default="true"> 

檢查數據屬性存在,如果它確實return true在點擊處理程序繼續默認行爲:

var sm_controller_1 = new ScrollMagic.Controller(); 

sm_controller_1.scrollTo(function(anchor_id) { 
     TweenMax.to(window, 2.0, { 
       scrollTo: { 
         y: anchor_id 
         autoKill: true 
       }, 
       ease: Cubic.easeInOut 
     }); 
}); 
jQuery(document).on("click", "a[href^=#]", function(e) { 
     if(e.currentTarget.dataset.default){ 
      return true; 
     } 
     var id = jQuery(this).attr('href'); 
     if(jQuery(id).length > 0) { 
       e.preventDefault(); 
       sm_controller_1.scrollTo(id); 
       if (window.history && window.history.pushState) { 
         history.pushState("", document.title, id); 
       } 
     } 
}); 
+0

感謝您的回答,並對我遲到的反應感到抱歉!問題是到錨點的鏈接都在導航菜單中,所以當我按照你的建議做時,所有鏈接的滾動動畫都會被停用,導航鏈接直接跳到錨點而不滾動。所以這給了我相同的結果,如果我只是停用動畫滾動,我不想要。我只能將它應用於我自己放置的其他網站上的鏈接(包括數據屬性),但如果有人設置了書籤或從我的網站複製了URL,它將不起作用。不過謝謝! – Johannes