前26行为我的导航栏和徽标中的所有链接提供了平滑的滚动,但是我不知道如何将其与我从另一个教程中获得的向上滚动按钮结合使用。有没有一种方法可以使所有链接在第一段代码中滚动,而不仅仅是导航栏中的元素?
$(document).ready(function(){
// Add scrollspy to <body>
$('body').scrollspy({target: ".navbar", offset: 50});
// Add smooth scrolling on all links inside the navbar
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// 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 (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
jQuery(window).scroll(function(){
if (jQuery(this).scrollTop() > 300) {
jQuery('.scrollToTop').fadeIn();
} else {
jQuery('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
jQuery('.scrollToTop').click(function(){
jQuery('html, body').animate({scrollTop : 0},800);
return false;
});
答案 0 :(得分:0)
您需要将导航栏链接和 scrollToTop链接的点击事件分开,并将 scrollToTop链接注册到点击事件中。因此您的代码将如下所示(假设您在导航栏上的链接中添加了一个类“ nav-link”):
$(document).ready(function(){
// Add scrollspy to <body>
$('body').scrollspy({target: ".navbar", offset: 50});
$('.scrollToTop').on('click',function(event){
event.preventDefault();
$('html, body').animate({scrollTop : 0}, 800);
});
// Add smooth scrolling on all links inside the navbar
$(".nav-link").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// 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 (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
jQuery(window).scroll(function(){
if (jQuery(this).scrollTop() > 300) {
jQuery('.scrollToTop').fadeIn();
} else {
jQuery('.scrollToTop').fadeOut();
}
});