2017-08-15 76 views
0

對,我已經有一段時間了。一個頁面滾動在主頁上(div id被定義)工作。單頁滾動:嘗試重定向到主頁並滾動到div - 不工作?

問題:從博客頁面,如果用戶點擊'聯繫人',我希望他們被重定向到主頁,然後動畫滾動到#contact-View div。

嘗試:我試圖檢查用戶是否點擊a標籤,然後檢查是否有使用if statement現在的博客頁面,然後重定向他們回到使用
window.location.href = home +sectionID;

主頁(和到div)

不工作。

的header.php(只有NAV位..)

  <nav class="header-nav"> 
       <!-- Create a navigation called primary in the header (front-end) --> 

       <?php $args = array('theme_location' => 'primary'); ?> 
       <?php wp_nav_menu($args) ?> 
      </nav> 

前page.php文件(家)

<div id="about-View" class="bg-1-wrapper"> #content </div> 
<div id="contact-View"> #content </div> 

的Javascript

jQuery(document).ready(function() { 

    // add a click listener to each <a> tags 
    setBindings(); 

    // burger nav 
    jQuery(".burger-nav").on("click", function() { 
     jQuery(".header-nav").toggleClass("open"); 
    }); 

}); 


function redirectToHome() { 

} 

/* ONE PAGE NAVIGATION FUNCTION */ 
    function setBindings() { 
    jQuery('a[href^="#"]').on('click', function(e) { 
     e.preventDefault(); 

     var home = "http://localhost/wordpress/"; 


     // Get the href attribute, which includes '#' already 
     var sectionID = jQuery(this).attr('href') + "-View"; 


     // if you're on blog page, first redirect to home -> div: #contact-View 
     if(document.URL.indexOf("http://localhost/wordpress/blog") >= 0){ 
      window.location.href = home +sectionID; 
       console.log(location.href); 


     } 

     // Animate the scroll 
     jQuery("html, body").animate({ 
     // Find target element 
     scrollTop: jQuery(sectionID).offset().top 
     }, 1000) 
    }); 
    } 

任何想法如何解決這個問題?

回答

0

有兩件事情可以更新的window.location.href值時發生:

  • 如果新值位於當前頁(通過使用錨),將跳轉到這一點無需重新加載頁面
  • 如果新值不位於當前頁面,JavaScript執行將停止,新的頁面將被要求並加載

animate功能不執行的問題是該類別中的後者酶。

解決方法是請求由額外不存在的錨點附加的新頁面(例如,#contact-View-scroll)。在新頁面上,您可以使用JavaScript檢查URL中的此特定錨點值,並在必要時執行滾動功能。

希望這有助於理解和解決您的問題。

更新:下面加

第1步一些示例代碼: 在博客頁面上,更新由以下內容前面加上井號標籤指的是主頁的鏈接:#scroll:(這樣http://localhost/wordpress/home#contact-Viewhttp://localhost/wordpress/home#scroll:contact-View

第2步: 將以下代碼片段添加到主頁。這將搜索#scroll:標記並激活animate函數(如果存在)。

jQuery(document).ready(function() { 
    // Get the hash from the URL 
    var hash = window.location.hash; 
    // If a hash exists && starts with "#scroll:" 
    if (hash.length and hash.indexOf('#scroll:') === 0) { 
    // Get the anchor name we are scrolling to 
    var selectionID = hash.substr('#scroll:'.length); 
    // Call the jQuery scroll function 
    jQuery("html, body").animate({ 
     scrollTop: jQuery('#'+selectionID).offset().top 
    }, 1000); 
    } 
}); 

第3步:享受!

另請參閱https://jsfiddle.net/qcarmk2w進行演示。

+0

好的,JavaScript新手。你說過:請求附加了一個額外的不存在的錨點的新頁面。你能給我一個代碼示例,說明如何實現這個解決方案嗎? – Shaz

+0

當然,請查看我對該帖子所做的更改。 –