简体   繁体   English

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

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

I have a basic script that scrolls smoothly to anchored links when the user clicks on them.我有一个基本脚本,当用户点击它们时,它会平滑滚动到锚定链接。 My problem is that the smooth scroll only seems to work one way, when I click on one of the "go to top" links, the page just jumps...我的问题是平滑滚动似乎只能以一种方式工作,当我单击“转到顶部”链接之一时,页面只是跳转...

$(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/ https://jsfiddle.net/p70d4doq/22/

Any help would be much appreciated!任何帮助将非常感激!

Thanks, Andreas谢谢,安德烈亚斯

You forgot to add this bit:你忘了添加这一点:

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

Please do not give a fiddle that doesn't work!请不要给一个不起作用的小提琴! Check before posting links.在发布链接之前检查。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM