平滑滚动ID数组

时间:2018-06-17 08:24:37

标签: javascript jquery html

我想使用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;当我使用loop for main时它将无法正常工作。 有另一种方式吗? 我可以让动画在所有链接上工作但是如何为某些链接设置例外?

1 个答案:

答案 0 :(得分:1)

稍微更改了你的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>
&#13;
&#13;
&#13;