Jquery平滑滚动点击(两个方向,向下和向上)

jquery smooth scroll on click (both directions, down and up)

本文关键字:方向 两个 滚动 平滑 Jquery      更新时间:2023-09-26

我有一个基本的脚本,可以在用户点击锚定链接时平滑地滚动到锚定链接。我的问题是,平滑的滚动似乎只工作一种方式,当我点击一个"到顶部"的链接,页面只是跳转…

$(function(){
// Smooth scrolling for anchored links
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top
    }, 2000);
    return false;
  }
}
});
// Scroll down automatically on page load
$('html, body').animate({
scrollTop: $('.destination').offset().top
}, 2000);   
}); 
https://jsfiddle.net/p70d4doq/22/

任何帮助将非常感激!

谢谢,安德烈亚斯

您忘记添加这一点了:

$('a[href="#"]').click(function () {
    $('html, body').animate({
        scrollTop: 0
    }, 2000);
});

请不要给不工作的小提琴!发布链接前检查。

工作小提琴:https://jsfiddle.net/a5u0zzLr/