简体   繁体   English

如何平滑滚动到div id?

[英]How to smooth scroll to div id?

Im trying to set a div that I want to scroll to when I click a div in my menu. 我试图设置要在单击菜单中的div时要滚动到的div。 The problem is that the scroll to the div, is not scrolling to the div that I have in my code, It always scroll to something else on my page, strange. 问题是滚动到div并没有滚动到代码中的div,它总是滚动到页面上的其他地方,很奇怪。 Im using the code bellow: 我正在使用下面的代码:

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

ID #dns-scroll is the div that I want to scroll to. ID#dns-scroll是我要滚动到的div。

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

or 要么

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

Please check this link:- Smooth scroll to div id jQuery 请检查此链接:- 平滑滚动到div id jQuery

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

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