javascript - 从某些 ID 中排除滚动动画功能

标签 javascript jquery twitter-bootstrap animation scroll

我确实添加了 JavaScript 代码来为每个带有 ID 的 block 添加菜单滚动动画。然后我添加了 Bootstrap 的选项卡,由于我的动画滚动而弄乱了。

我想知道如何让我的滚动动画在 Bootstrap 选项卡上停止工作?

滚动动画代码

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 800);
        return false;
      }
    }
  });
});

Bootstrap 标签

<div role="tabpanel">

  <!-- Nav tabs -->
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
    <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
    <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
    <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
  </ul>

  <!-- Tab panes -->
  <div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="home">...</div>
    <div role="tabpanel" class="tab-pane" id="profile">...</div>
    <div role="tabpanel" class="tab-pane" id="messages">...</div>
    <div role="tabpanel" class="tab-pane" id="settings">...</div>
  </div>

</div>

最佳答案

我遇到了同样的问题,然后就这样解决了。在代码的开头:

$(function() {
$('a[href*=#]:not([href=#])').click(function() {`

您必须向“a”元素添加一个类。假设您添加了 scrollnav 类。

它会是这样的:

$(function() {
$('a.scrollnav[href*=#]:not([href=#])').click(function() {`

所以这段代码(平滑滚动)将只对具有此类的 a 元素起作用。

您的 Java 应如下所示:

$(function() {
    $('a.scrollnav[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var target = $(this.hash);
              target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              if (target.length) {
                 $('html,body').animate({
                     scrollTop: target.offset().top
                 }, 800);
                 return false;
              }
          }
     });
});

并且菜单(或其他导航链接)中的每个 a 元素都必须具有 scrollnav 类。

关于javascript - 从某些 ID 中排除滚动动画功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27184627/

相关文章:

javascript - 迭代 Google Apps 脚本中的对象并打印到 Google 表格

javascript - 基本理解题 : objects scope

jquery - 无法按照常见问题解答示例使用 jquery 禁用表单元素

javascript - 刷新时随机数

javascript - CSS3 过渡效果问题

javascript - 使用 Ajax 更改 ASP.NET 中的 img src

javascript - 在下拉列表中加载时间并将其保存在 mysql 数据库中

javascript - 关闭警告框后 URL 中的问号

javascript - 如何将变量从gridview yii发送到javascript

html - ie7 与 bootstrap CSS 问题与 div 和定位