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

时间:2013-09-02 14:03:48

标签: javascript jquery scroll anchor smooth

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

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

    <a name="urunler"></a>
<ul>
    <li><a href="#ppanjur" class="uruna">Plastik Panjur</a></li>
    <li><a href="#ipanjur" class="uruna">Alüminyum (İthal / Yalıtımlı) Panjur</a></li>
    <li><a href="#opanjur" class="uruna">Otomatik Panjur</a></li>
    </ul>

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

  1. 我需要通过点击方法了解我的链接的完整语法(它们都有相同的类)
  2. 我应该从链接中删除href park吗?
  3. 等待你的帮助&amp;还在搜索

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

        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'));
    });
    

3 个答案:

答案 0 :(得分:2)

HTML:

<ul>
    <li><a href="#ppanjur" class="uruna">Plastik Panjur</a></li>
    [...]
</ul>

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));
});

答案 1 :(得分:1)

我注意到,通过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来模仿它。对于旧浏览器that don't support pushState,它会滚动到正确的位置,但它不会更新地址位置。

答案 2 :(得分:0)

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

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

function scrollToElement (selector) {
  $('html, body').animate({
    scrollTop: $(selector).offset().top
  }, 2000);    
};

$(document).on('click', 'a.uruna', function () {
    scrollToElement($(this).attr('href'));
});
相关问题