平滑滚动到内部链接的最佳方法

我已经搜索过并看到很多关于这个主题的例子,但我无法找到最好的方法。

我只是对JS和jQuery有点熟悉,我想问一下平滑滚动。

  

我有这样的导航。 这会不稳定地滚动。 但我想慢慢来。 这是最短最简单的方法吗? 我对JS更熟悉,我不想下载和使用JS插件。

  1. 我需要通过单击方法知道我的链接的完整语法(它们都有相同的类)
  2. 我应该从链接中删除href park吗?

等待你的帮助仍然在寻找

编辑!!!:在这种情况下,我只需要一个class级。 是否可以为多个类提供此属性?

  function scrollToElement (selector) { $('html, body').animate({ scrollTop: $(selector).offset().top }, 2000); }; $(document).on('click', 'a.uruna', function () { scrollToElement($(this).attr('href')); }); 

我有(’click’,’a.uruna’,function(),我怎么能在这里插入另一个类,或者我应该写:

 $(document).on('click', 'a.uruna', function () { scrollToElement($(this).attr('href')); }); $(document).on('click', 'a.new', function () { scrollToElement($(this).attr('href')); }); 

HTML:

  

JS:

 function scrollToElement (selector) { $('html, body').animate({ scrollTop: $(selector).offset().top }, 2000); }; $(document).on('click', 'a.uruna', function () { scrollToElement($(this).attr('href')); }); 

要么

 function scrollToElement (obj) { $('html, body').animate({ scrollTop: obj.offset().top }, 2000); }; $(document).on('click', 'a.uruna', function () { scrollToElement($(this)); }); 

我注意到,通过JohnJohnGa的回答,你会得到一个“闪烁”(至少对于谷歌浏览器),页面会立即弹出到锚点href位置,然后再顺利回滚到它之前。 对于快速计算机来说,这可能并不明显,但在我正在研究的计算机上它肯定是显而易见的。 为了解决这个问题,我做了以下事情:

 $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); window.history.pushState(null, null, $($anchor.attr('href')).selector); }); 

注意,这可以防止触发默认事件,然后使用window.history.pushState来模仿它。 对于不支持pushState的旧浏览器,它将滚动到正确的位置,但它不会更新地址位置。

生活演示: http : //jsfiddle.net/wVEAy/2/

请注意,对于这种情况,您需要具有与链接的href标记中指定的元素具有相同id的元素:

 function scrollToElement (selector) { $('html, body').animate({ scrollTop: $(selector).offset().top }, 2000); }; $(document).on('click', 'a.uruna', function () { scrollToElement($(this).attr('href')); });