2017-08-15 52 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

当然,请查看我对该帖子所做的更改。 –