如何平滑滚动到div id?

时间:2016-10-08 14:03:15

标签: javascript jquery html css

当我点击菜单中的div时,我试图设置一个我要滚动的div。问题是滚动到div,不是滚动到我的代码中的div,它总是滚动到我的页面上的其他东西,奇怪。 我正在使用下面的代码:

$(".dns-anchor").click(function() {
    $('html, body').animate({
        scrollTop: $("#dns-scroll").offset().top
    }, 2000);
});

ID#dns-scroll是我要滚动到的div。

1 个答案:

答案 0 :(得分:0)

$(function() {
  $('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
        }, 1000);
        return false;
      }
    }
  });
});

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

请检查此链接: - Smooth scroll to div id jQuery