Bootstrap 4 activate.bs.scrollspy事件未触发 [英] Bootstrap 4 activate.bs.scrollspy event is not firing

查看:158
本文介绍了Bootstrap 4 activate.bs.scrollspy事件未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Bootstrap v4.0.0

I'm using Bootstrap v4.0.0

我已经包含了必要的JavaScript文件(jQuery,popper和Bootstrap)以及必要的CSS文件.

I have included the necessary JavaScript files (jQuery, popper and Bootstrap) and the necessary CSS files as well.

这是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 不触发.

The menu items get highlighted properly when scrolling, but the JavaScript event activate.bs.scrollspy is not firing.

我还尝试将事件挂接到navbar本身,但是它也不会触发:

I also tried to hook the event to the navbar itself, but it does not fire either:

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

我曾经在Bootstrap 3中使用此代码,并且工作得很好.

I used to use this code with Bootstrap 3 and worked just fine.

有什么想法吗?

谢谢.

推荐答案

由于某种原因在此处解释为,当您将body用作间谍元素时,该事件将在window上激活.

For some reason explained here, when you use body for the spy element the event gets activated on the window.

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

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

编辑

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

The target element can be obtained in the 2nd event param:

      $(window).on('activate.bs.scrollspy', function (e,obj) {
          console.log(obj.relatedTarget);
      });

这篇关于Bootstrap 4 activate.bs.scrollspy事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆