Bootstrap 使用数据属性的词缀只对页面重新加载有效

Bootstrap affix using data-attributes only works on page reload

我正在使用 bootstrap 通过数据属性附加功能的 Rails4 应用程序。

我正在使用这样的数据属性:

<div data-spy="affix" data-offset-top="300" data-offset-bottom="615">
...stuff...
...stuff...
...stuff...
</div>

我唯一的 CSS 词缀 类 如下:

.affix {
    width: 255px;
    margin-top: -300px;
}

.affix-bottom {
    position: relative;
}

.affix-top {
    position: relative;
}

当我重新加载页面时一切正常,除了当我最初从我的网络应用程序的另一个页面导航到它时它不起作用。

似乎其他人对此有困难,这是一个 turbolinks 问题。尝试了他们所有的方法,但没有任何效果: 没有尝试使用 jquery-turbolinks 所以我最终一起删除了 turbolinks.. 如果有人知道我可以做到这一点,我宁愿使用 turbolinks 如果我能让它工作。 关于为什么会发生这种情况的任何想法?

我认为您需要为 CSS 中的 .affix 元素设置顶部 属性。负边距可能会导致词缀偏移量计算出现问题 -

.affix{
   top: 300px; /* Set the top position of pinned element */
}

检查此 URL,可能会对您有所帮助 - http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-affix.php

我刚刚删除了 turbolinks 以完成这项工作。找不到使用 Turbolinks 进行此操作的方法。

我最终删除了数据属性并在页面加载后初始化词缀(我使用 jquery.turbolinks),如下所示:

  $(document).ready ->
    $('#myAffix').affix({
      offset:
        top: 100,
        bottom: 0
    })

(请原谅我的咖啡脚本!)

如果您需要使用数据属性设置偏移量等(即您站点上的每个词缀都有不同的偏移量)。您可以创建自己的数据属性并使用 $('#myAffix').data('offset-top') 获取它们。