如何使用Bootstrap实现平滑滚动

How do I implement smooth scrolling with Bootstrap?

本文关键字:平滑 滚动 实现 Bootstrap 何使用      更新时间:2023-09-26

我已经用几个不同的jQuery插件挣扎了两个小时,试图让流畅的滚动为我的网站工作。

这是目前的相关代码:

<div class="row-fluid">
 <header class="span12 hero-unit">
 <ul class="thumbnails">
  <li class="span3"></li>
  <li class="span2">
   <a href="#Blog" class="thumbnail">
   <img src="images/nav_icon-01.png" alt="Blog"/>
   </a>
  </li>
  <li class="span2">
   <a href="#Projects" class="thumbnail">
   <img src="images/nav_icon-02.png" alt="Projects"/>
   </a>
  </li>
  <li class="span2">
   <a href="#Contact" class="thumbnail">
   <img src="images/nav_icon-03.png" alt="Contact"/>
   </a>
  </li>
  <li class="span3"></li>
 </ul>
 </header>
</div>

我已经删除了我所有的JS代码(因为我知道我没有正确使用它们中的任何一个,我想重新开始(,除了这一个,因为这似乎真的有效,但只在页面加载时激活,我想知道是否有可能在点击时使其有效。

<script type="text/javascript">
$('html, body').animate({
scrollTop: $("#Blog").offset().top
}, 2000);
</script>

mddw提到的内容有效,除了它会导致相当大的闪烁,除非你阻止浏览器的默认操作如下(此外,他的大括号顺序错误(:

$('a.thumbnail').on('click', function(event) {
  var to = $(this).attr('href');
  $('html, body').animate({ scrollTop: $(to).offset().top }, 500);
  event.preventDefault();
});

我不知道这个插件,但根据它的工作原理,比如(假设最近的JQuery(:

$('a.thumbnail').on('click', function() {
  var to = $(this).attr('href'); // $(this) is the clicked link. We store its href.
  $('html, body').animate({ scrollTop: $(to).offset().top }, 2000);
)};

如果您的JQuery是<1.7,您可以尝试.click((,无论JQuery版本如何,它都能工作:

$('a.thumbnail').click(function() {
  var to = $(this).attr('href');
  $('html, body').animate({ scrollTop: $(to).offset().top }, 2000);
});