我在网站http://deliciousproductions.com.au有一个导航栏,导航栏中的href链接似乎不起作用,#about的href内容有效,但不适用于像家一样的实际链接。
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#home">Delicious Productions</a>
</div>
<div class="collapse navbar-collapse" id="navbar">
<ul class="nav navbar-nav navbar-right">
<li><a href="http://deliciousproductions.com.au">HOME</a></li>
<li><a href="#about">ABOUT</a></li>
<li><a href="http://deliciousproductions.com.au/recipes">RECIPES</a></li>
<li><a href="#contact">CONTACT</a></li>
</ul>
</div>
</div>
</nav>
我觉得它应该只是工作但是因为onclick可能这个脚本干扰了吗?
$(document).ready(function(){
// Add smooth scrolling to all links in navbar
$(".navbar a").on('click', function(event) {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (900) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 1600, 'easeInOutCubic', function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
});
})
欢呼,还是防止默认?
答案 0 :(得分:1)
您是对的$(".navbar a")
选择器会选择所有链接,并阻止默认行为event.preventDefault();
尝试将一个类scroll
添加到a
锚标记,并将您的选择器修改为$(".navbar a.scroll")
选择器。
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#home">Delicious Productions</a>
</div>
<div class="collapse navbar-collapse" id="navbar">
<ul class="nav navbar-nav navbar-right">
<li><a href="http://deliciousproductions.com.au">HOME</a></li>
<li><a class="scroll" href="#about">ABOUT</a></li>
<li><a href="http://deliciousproductions.com.au/recipes">RECIPES</a></li>
<li><a class="scroll" href="#contact">CONTACT</a></li>
</ul>
</div>
</div>
</nav>
$(document).ready(function(){
// Add smooth scrolling to all links in navbar
$(".navbar a.scroll").on('click', function(event) {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (900) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 1600, 'easeInOutCubic', function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
});
})