I created a one page layout and multiple section and added links to the navbar for those sections and I have a jQuery for smooth scrolling withing the page . But if I want to link to other pages it simply does not work and when I remove the Jquery it works just fine.
$(function(){
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
});
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li><a href="#hero">Home</a></li>
<li><a href="service.html">Services</a></li>
<li><a href="#contact-form">Contact</a></li>
<li><a href="#about-us">About Us</a></li>
</ul>
</div>
</div>
</nav>
<!-- begin snippet: js hide: false console: true babel: false -->
答案 0 :(得分:2)
这会阻止链接正常工作:
event.preventDefault();
我建议在 anchors 的链接上添加一个类,并更新jQuery以定位这些类。 不要在要链接到其他页面的链接上包含该类
<ul class="nav navbar-nav">
<li><a href="#hero" class="anchor-link">Home</a></li>
<li><a href="service.html">Services</a></li>
<li><a href="#contact-form" class="anchor-link">Contact</a></li>
<li><a href="#about-us" class="anchor-link">About Us</a></li>
</ul>
$(function(){
$(document).on('click', '.anchor-link', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
});
答案 1 :(得分:1)
您将点击事件绑定到所有链接元素,而不仅仅是同一页面中的链接。更改选择器,使其仅捕获带有片段的链接:
...
$(document).on('click', 'a[href*="#"]', function(event){
...
答案 2 :(得分:0)
Would be better if you add any class to <a>
that contains #link and then pimp you JS like this:
$(function(){
$('.CHOSEN_CLASS').on('click', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
});