代码之家  ›  专栏  ›  技术社区  ›  zed

启动引导4。英国标准。scrollspy事件未触发

  •  17
  • zed  · 技术社区  · 8 年前

    我正在使用Bootstrap v4.0.0

    我已经包括了必要的JavaScript文件(jQuery、popper和Bootstrap)和必要的CSS文件。

    这是HTML:

    <body data-spy="scroll" data-target="#my-navbar-collapse" data-offset="100">
        <!-- ... -->
        <div class="collapse navbar-collapse" id="my-navbar-collapse">
            <ul class="nav navbar-nav" role="tablist">
                <li class="nav-item">
                    <a class="nav-link" href="#one">One</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#two">Two</a>
                </li>
            </ul>
        </div>
        <!-- ... -->
        <section id="one">
            Content.
        </section>
        <!-- ... -->
        <section id="two">
            More content.
        </section>
        <!-- ... -->
        <script>
            $(function() {
                // As per the official docs: 
                // https://getbootstrap.com/docs/4.0/components/scrollspy/#events
                $('[data-spy="scroll"]').on('activate.bs.scrollspy', function() {
                    console.log("This event is not firing...");
                });
            });
        </script>
    </body>
    

    滚动时,菜单项会正确突出显示,但JavaScript事件 activate.bs.scrollspy 没有点火。

    我还试图把这件事与 navbar 但它也不会开火:

    $('#my-navbar-collapse').on('activate.bs.scrollspy', function () {
        console.log("Not firing either...");
    })
    

    我曾经在Bootstrap 3中使用过这段代码,并且工作得很好。

    有什么想法吗?

    非常感谢。

    2 回复  |  直到 8 年前
        1
  •  35
  •   Carol Skelly    8 年前

    出于某种原因 explained here ,当您使用 body 对于spy元素,在 window .

            $(window).on('activate.bs.scrollspy', function () {
                console.log("This event is not firing...");
            });
    

    演示: https://www.codeply.com/go/aN4tfy0zU0

    编辑

    可在第二个事件参数中获取目标元素:

          $(window).on('activate.bs.scrollspy', function (e,obj) {
              console.log(obj.relatedTarget);
          });
    
        2
  •  1
  •   Q Studio    6 年前

    @kim给出了正确的答案,但我还需要挂钩到一个滚动结束事件,它似乎不存在-因此使用超时创建了一些简单的东西:

    // reset scroll watcher ##
    clearTimeout( jQuery.data(this, 'scrollTimer'));
    
    jQuery(window).on('activate.bs.scrollspy', function ( e,obj ) {
            
        // console.log(obj.relatedTarget);
            
        jQuery.data( this, 'scrollTimer', setTimeout(function() {
                
            // console.log("Didn't scroll in 1/4 sec..");
    
            // no scroll items are marked as active ##
            if ( ! jQuery(".scrollspy-item.active")[0]){ 
    
                // console.log("Can't fund any active scrollspy items..");
    
                // add class to parent again ##
                jQuery(".list-group-item.current").addClass( 'active' );
    
            }
    
        }, 250 ) );
    
    });
    

    在本例中,我检查是否有任何“scrollspy项”标记为活动,然后将活动类添加到父项,因为我们在侧栏菜单中使用了scrollspy。