jQuery 动画方法的持续时间 属性 不工作

jQuery Animate Method's Duration Property not working

我试图在点击导航栏链接时在我的网页上应用平滑的滚动动画。

但是 animate 方法不起作用,单击链接时链接不会转到下一部分,因此单击链接时我停留在最上面的部分。

我使用 minified 版本解决了这个问题。 jQuery CDN 而不是 slim minified.

虽然链接转到了它们的指定部分,但平滑滚动效果仍然不适用。他们只是跳到下一个,就好像我的 jQuery 中的 duration 属性 不存在一样。

我是不是做错了什么?我正在使用 Bootstrap 4 我什至尝试包括 jQuery UI CDN 但它仍然没用。

另外,我在我的 console output 上发现了这个问题,这可能是导致问题的原因吗?

// Doesn't do the duration
$(".navbar a").click(function(e) {
  e.preventDefault();

  $("html, body").animate({
    scrollTop: $(this.hash).offset().top
  }, 1000);
});
<!-- The CDN's that I'm using -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>

Changed the code to:

$(".navbar a").click(function(e) {
  e.preventDefault();
    
  document.querySelector(this.hash).scrollIntoView({
    behavior: "smooth" 
  });
});

here's the reference, thanks again! @jqueryHtmlCSS

我没有发现你的代码有问题。在这里测试:

$(function() {
  function jumpTo(el, ms) {
    $("html, body").animate({
      scrollTop: $(el).offset().top - 2
    }, ms);
  }

  $(".navbar a").click(function(e) {
    e.preventDefault();
    jumpTo(this.hash, 1000);
  });
});
.navbar,
.content {
  padding-top: 10px;
}

.content {
  height: 1400px;
}

.article {
  width 95%;
  height: 340px;
  border: 1px solid #ccc;
  border-radius: 6px;
  margin-top: 10px;
}

#bar-1 {
  background: #ccd;
}

#bar-2 {
  background: #cdc;
}

#bar-3 {
  background: #dcc;
}
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<a id="top"></a>
<div class="navbar">
  <a href="#bar-1">Bar 1</a>
  <a href="#bar-2">Bar 2</a>
  <a href="#bar-3">Bar 3</a>
</div>
<div class="content">
  <div id="bar-1" class="article">Bar 1</div>
  <a href="#top">Back to Top</a>
  <div id="bar-2" class="article">Bar 2</div>
  <a href="#top">Back to Top</a>
  <div id="bar-3" class="article">Bar 3</div>
  <a href="#top">Back to Top</a>
</div>

我觉得很顺利。