教程 > bootstrap 5 教程 > 阅读:413

bootstrap5 滚动监听(scrollspy)——迹忆客-ag捕鱼王app官网

bootstrap scrollspy 是一种导航机制,它根据滚动位置自动突出显示导航链接,以指示访问者当前在页面上的位置。

如果使用书签链接将访问者引导到包含大量内容的页面的不同部分,scrollspy 将使您的网页更加优雅和易于访问。

scrollspy 有以下要求才能正常运行:

  • 它必须用于 bootstrap 导航或列表组组件。
  • 您必须应用样式 position:relative; 在您监视的元素上,通常是 元素。 但是,如果您正在监视
    或 以外的任何元素,请确保另外应用高度和溢出-y:滚动; 在上面。
  • 锚点 (

section one

this is section one content...


section two

this is section two content...


section three

this is section three content...


通过 data 属性创建 scrollspy

我们可以通过 data 属性轻松地将滚动监视行为添加到导航栏,而无需编写任何 javascript 代码。 让我们试试下面的例子,看看它是如何工作的:


    
    

section 1

this is section 1 content...


section 2

this is section 2 content...


section 3

this is section 3 content...


section 4

this is section 4 content

section 4.1

this is section 4.1 content...

section 4.2

this is section 4.2 content...

section 4.3

this is section 4.3 content...


section 5

this is section 5 content...

你可能想知道这段代码是关于什么的。 好吧,为了更好的理解,让我们将这个scrollspy示例代码的每一部分都一一梳理一遍。

通过 javascript 创建 scrollspy

也可以使用 javascript 手动添加 scrollspy — 只需在 javascript 代码中使用导航栏的 id 或类选择器调用 scrollspy() bootstrap 方法即可。

document.addeventlistener("domcontentloaded", function(){
    var myscrollspy = new bootstrap.scrollspy(document.body, {
        target: "#mynavbar"
    })
});

查看笔记

扫码一下
查看教程更方便
网站地图