javascript - 平滑滚动 ID 数组

标签 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 上工作;当我对 main 使用循环时,它将无法正常工作。 还有别的办法吗? 我可以使动画在所有链接上运行,但如何对某些链接进行异常(exception)处理?

最佳答案

稍微改变一下你的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>

关于javascript - 平滑滚动 ID 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50894948/

相关文章:

html - 使用位置 :absolute while keeping it inside the document flow

javascript - 我应该使用 window.onload 事件

javascript - 以日期为键的映射无法正确检索项目

javascript - 未定义不是函数,所见即所得 drupal7

javascript - 可拖动的 Highcharts SVG 元素

javascript - 使用 jQuery 表单插件通过 Ajax 上传文件时不调用错误处理程序

javascript - HTML 表格背景颜色更改不适用于从 PHP 获取的表格

javascript - 使用 JavaScript 和 Google Gears 处理文件上传,有更好的解决方案吗?

Javascript - 缺少输入的文本区域上的红色轮廓

javascript - 剑道用户界面 : Unable to bind data to list view using MVVM