【问题标题】:Bootstrap 3 - affix is not changing classesBootstrap 3 - 词缀不改变类
【发布时间】:2015-05-27 12:15:57
【问题描述】:

我有一个打开模式的按钮。此按钮应始终可见。如果用户向下滚动页面,按钮应该“固定”在顶部。

我使用引导程序 v3.1.1,affix.js 已加载到头部,并将 "affix-top" 类附加到我的按钮上。

但是当我滚动时 - 我已经尝试了几种实现变体 - affix-top 类不会更改为 affix

这是我的代码。

HTML:

  <button class="btn btn-primary m-t-10 m-b-10"
            id="standard-questions-button"
            type="button"
            data-toggle="modal"
            data-target="#standard-questions-modal">
      Show Questions
    </button>

JS:

$('#standard-questions-button').affix({
    offset: {top: $('#standard-questions-button').position().top}
});

// for testing only
$('#standard-questions-button').on('affix.bs.affix', function () {
    alert('affix');
})

CSS:

#standard-questions-button.affix-top {
  color: red;
  position: static;
  margin-top:25px;
  width:228px;
}

#standard-questions-button.affix {
  color: green;
  top:25px;
  float: right;
  width:228px;
}

方法 2(也不起作用:包装在函数中)

   $('#standard-questions-button').affix({
        offset: {top: function(){return $('#standard-questions-button').position().top}}
    });
  • 我该如何解决这个问题?
  • 我错过了什么吗?

【问题讨论】:

  • 你可以准备jsfiddle.net
  • 很奇怪,小提琴按预期工作...jsfiddle.net/Lz0szvwe
  • 用你的第二种方法,用函数,也尝试console$('#standard-questions-button').position().top的值,你的JS在你的CSS加载之前执行的可能性很小,你得到一个错误的top价值。

标签: javascript jquery css twitter-bootstrap affix


【解决方案1】:

我遇到了完全相同的问题。也许你也有类似的问题。

在引导脚本中(我使用的是 2.3.2 版本)有一个代码片段将事件处理程序分配给窗口的滚动:

     this.$window = $(window)
    .on('scroll.affix.data-api', $.proxy(this.checkPosition, this))

我意识到在我的代码中根本没有触发滚动事件,因此没有更改类。当我仅将此片段更改为:

     this.$window = $('#main_container')
    .on('scroll.affix.data-api', $.proxy(this.checkPosition, this))

它终于开始工作了。只需检查您在网页上滚动的元素是什么,并将其设置在引导程序的 Affix 函数定义中。

您可能会发现这有助于检查您是否能够滚动窗口:

    $( window ).scroll(function() {
      alert("scroll");
    });

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 2014-07-15
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多