首页 > 解决方案 > 平滑滚动 ID 数组

问题描述

我想使用 jQuery 平滑滚动 HTML 网站中的某些链接。

var main = ["#main1", "#main2", "#main3", "#main4"]
$(document).ready(function () {
    $("a").on('click', function (event) {
            if (this.hash ==|| this.hash == "#top") {
                event.preventDefault();
                var hash = this.hash;
                $('html, body').animate({
                    scrollTop: $(hash).offset().top
                }, 800, function () {
                    window.location.hash = hash;
                });
            }
    });
});

我需要这个动画在我的主数组和#top ID 上工作;当我对主使用循环时,它不能正常工作。还有其他方法吗?我可以使动画适用于所有链接,但是如何为某些链接设置例外?

标签: javascriptjqueryhtml

解决方案


稍微改变了你的js

$("a").on('click', function(event) {
     if (this.hash && main.includes(this.hash)) {
      event.preventDefault();
      var hash = this.hash;
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function() {
        window.location.hash = hash;
      });

基本上这条线if (this.hash && main.includes(this.hash)) {

$(document).ready(function() {
  var main = ["#main1", "#main2", "#main3", "#main4", "#top"];
  $("a").on('click', function(event) {
    if (this.hash && main.includes(this.hash)) {
      event.preventDefault();
      var hash = this.hash;
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function() {
        window.location.hash = hash;
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="top">
</div>
<div id="main1" style="height: 200px;background-color:red;">
  <a href="#main2">
        Go to Main 2
        </a>
  <br/>
  <a href="#main5">
        Go to Main 5 withoout animation
        </a>

</div>
<div id="main2" style="height: 200px;background-color:skyblue;">
  <a href="#main3">
        Go to Main 3
        </a>
  <br/>
  <a href="#top">
                Go to Top
        </a>
</div>
<div id="main3" style="height: 200px;background-color:green;">
  <a href="#main4">
                Go to Main 4
        </a>
  <br/>
  <a href="#top">
                Go to Top
        </a>
</div>
<div id="main4" style="height: 200px;background-color:yellow;">
  <a href="#main1">
                Go to Main 1
        </a>

</div>
<div id="main5" style="height: 200px;background-color:red;">
  <a href="#main1">
                Go to Main 1
        </a>

</div>


推荐阅读