【问题标题】:Smooth scroll for link with anchor平滑滚动与锚链接
【发布时间】:2018-06-07 04:52:57
【问题描述】:

我正在寻找如何为 example.com/subpage#anchor 等链接添加平滑滚动的方法。
我正在尝试使用此代码

 $(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top 
    }, 500);
});

但它不适用于 example.com/subpage#anchor

【问题讨论】:

  • $.attr 似乎不是 api 中的方法,只有 $.fn.attr 是。尝试改用$(this.getAttribute('href'))
  • 什么都没有改变,它仍然不起作用,但现在我得到一个错误 TypeError: $ is not a function
  • 我打算给出一个显示 getAttribute() 的答案,但您的逻辑似乎可以正常工作。

标签: javascript jquery scroll


【解决方案1】:

实际上,您的逻辑似乎运行良好,无需任何修改。

$(document).on('click', 'a[href^="#"]', function(event) {
  event.preventDefault();

  $('html, body').animate({
    scrollTop: $($.attr(this, 'href')).offset().top
  }, 500);
});
#container menu {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  margin: 0;
  padding: 0;
  background-color: rgb(128, 128, 128);
}

menu li {
  display: inline-block;
  min-width: 32.75%;
  text-align: center;
  background-color: rgb(152, 152, 152);
}

#home,
#aboutUs,
#contact {
  display: block;
  min-height: 600px;
}

#home {
  background-color: red;
  margin-top: 19px;
}

#aboutUs {
  background-color: green;
}

#contact {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <menu>
    <li><a href="#home">Home</a></li>
    <li><a href="#aboutUs">About Us</a></li>
    <li><a href="#contact">Contact Us</a></li>
  </menu>

  <div id="home"></div>
  <div id="aboutUs"></div>
  <div id="contact"></div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2013-07-17
    • 2022-07-13
    • 1970-01-01
    相关资源
    最近更新 更多