使用 Codeigniter/PHP 和 this Bootstrap template .该模板包括主页上的页面滚动功能。
我有一个 header.php
将用于在每个页面上显示主导航的模板。
这个主导航代码;
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" href="#home">Home</a>
</li>
<li>
<a class="page-scroll" href="#items">Items</a>
</li>
<li>
<a class="page-scroll" href="#features">Features</a>
</li>
<li>
<a class="page-scroll" href="#contact">Contact</a>
</li>
</ul>
</div>
Jquery代码;
(function($) {
"use strict"; // Start of use strict
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(document).on('click', 'a.page-scroll', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 100
});
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 50
}
})
})(jQuery); // End of use strict
一切都按预期工作,但仅限于主页 (home.php
)。
我需要创建一些额外的页面(例如 items.php
),这是标题导航不起作用的地方。
当我访问items.php
时并将鼠标悬停在 Contact
上菜单链接,网址为/items#contact
.它正在寻找 #contact
锚定在 items
页。相反,我想去 #contact
锚定在 home
页面。
所以,为了让它工作,我添加了 <?php echo base_url();?>
到我的菜单链接-制作它们<a class="page-scroll" href="<?php echo base_url();?>#items">Items</a>
.我的主页 URL 是 http://localhost/ci
这有效,而且在 items
上页面成功将我带到 home page
上的正确 anchor .
但是在添加 <?php echo base_url();?>
之后看起来像是,主页滚动不起作用。单击链接会将我带到正确的 anchor ,但它不会滚动,而是“跳转”。
可能是非常简单的事情!有什么想法吗?
最佳答案
您可以使用此功能。它使用 javascript 路径名来查找当前页面是否为主页。如果当前页面是主页,它将滚动到所需的位置,否则它将导航到主页。 (使用您的主页路径名而不是“/”)
(function($) {
"use strict"; // Start of use strict
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(document).on('click', 'a.page-scroll', function(event) {
/*******USE YOUR HOMEPAGE PATHNAME HERE*****/
if(window.location.pathname == '/') {
var url = $(this).attr("href");
var hash = url.split('#')[1];
$('html, body').stop().animate({
scrollTop: ($('#' + hash).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
}
});
})(jQuery); // End of use strict
关于javascript - 页面滚动和 JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43113206/