[英]One-Page Scroll: Trying to redirect to home page and scroll to the div - Not Working?
是的,我已經有一段時間了。 一頁滾動可在主頁上進行(定義div ID)。
問題:在博客頁面上,如果用戶單擊“聯系人”,我希望將他們重定向到主頁,然后將動畫滾動到#contact-View
div。
嘗試:我嘗試檢查用戶是否單擊a
標簽,然后使用if statement
檢查是否存在博客頁面,然后使用重定向到主頁(和div)
window.location.href = home +sectionID;
不工作
header.php(僅導航位..)
<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>
front-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)
});
}
任何想法如何解決該問題?
更新window.location.href
的值時,可能會發生兩件事:
在這種情況下, animate
功能無法執行的問題是后者。
一種解決方案是請求新頁面附加一個額外的不存在的定位符(例如#contact-View-scroll )。 在新頁面上,您可以使用JavaScript來檢查URL中的此特定錨值,並在必要時執行滾動功能。
希望這有助於理解和解決您的問題。
更新 :在下面添加了一些示例代碼
第1步:在博客頁面上,通過將以下內容添加到主題標簽之前,更新引用主頁的鏈接: #scroll:
例如, http:// localhost / wordpress / home#contact-View變為http:// 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以獲取演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.