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);
});