滚动监控(Scrollspy)

根据滚动位置自动更新Bootstrap 导航或列表组组件,以指示视口中当前处于活动状态的链接。

工作原理

S滚动监控正常运行的几个要求:

  • 必须使用在Bootstrap导航元件nav或列表群组list group.
  • 滚动监控需要在被监控的元素上设定position: relative;,通常是.
  • 锚(a)是必要的,且必须指向到该元素的id.

成功运行后,您的导航或列表群组将相应更新,根据相对应的目标将.active从一个项目移动到下一个项目。

可滚动内容与键盘兼容性

如果要制作可滚动容器(body除外),请确定已经设定height和overflow-y: scroll;旁边带有tabindex=“0”,以确保键盘兼容性。

导航栏中的示例

滚动导航下方的块,并查看active class的变化。下拉菜单项目也会显示同样效果

@fat

Placeholder content for the scrollspy example. You got the finest architecture. Passport stamps, she's cosmopolitan. Fine, fresh, fierce, we got it on lock. Never planned that one day I'd be losing you. She eats your heart out. Your kiss is cosmic, every move is magic. I mean the ones, I mean like she's the one. Greetings loved ones let's take a journey. Just own the night like the 4th of July! But you'd rather get wasted.

@mdo

Placeholder content for the scrollspy example. 'Cause she's the muse and the artist. (This is how we do) So you wanna play with magic. So just be sure before you give it all to me. I'm walking, I'm walking on air (tonight). Skip the talk, heard it all, time to walk the walk.

one

Placeholder content for the scrollspy example. Takes you miles high, so high, 'cause she’s got that one international smile. There's a stranger in my bed, there's a pounding in my head. Oh, no. In another life I would make you stay. ‘Cause I, I’m capable of anything. Suiting up for my crowning battle. Used to steal your parents' liquor and climb to the roof. Tone, tan fit and ready, turn it up cause its gettin' heavy. Her love is like a drug. I guess that I forgot I had a choice.

two

Placeholder content for the scrollspy example. It's time to bring out the big balloons. I'm walking, I'm walking on air (tonight). Yeah, we maxed our credit cards and got kicked out of the bar. Yo, shout out to all you kids, buying bottle service, with your rent money. I'm ma get your heart racing in my skin-tight jeans. If you get the chance you better keep her. Yo, shout out to all you kids, buying bottle service, with your rent money.

three

Placeholder content for the scrollspy example. If you wanna dance, if you want it all, you know that I'm the girl that you should call. Walk through the storm I would. So let me get you in your birthday suit. The one that got away. Last Friday night, yeah I think we broke the law, always say we're gonna stop. 'Cause she's a little bit of Yoko, And she's a little bit of 'Oh no'. I want the jaw droppin', eye poppin', head turnin', body shockin'. Yeah, we maxed our credit cards and got kicked out of the bar.

And some more placeholder content, for good measure.

<nav id="navbar-example2" class="navbar navbar-light bg-light px-3">
  <a class="navbar-brand" href="#">Navbar</a>
  <ul class="nav nav-pills">
  <li class="nav-item">
  <a class="nav-link" href="#fat">@fat</a>
  </li>
  <li class="nav-item">
  <a class="nav-link" href="#mdo">@mdo</a>
  </li>
  <li class="nav-item dropdown">
  <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false">Dropdown</a>
  <ul class="dropdown-menu dropdown-menu-end">
    <li><a class="dropdown-item" href="#one">one</a></li>
    <li><a class="dropdown-item" href="#two">two</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item" href="#three">three</a></li>
  </ul>
  </li>
  </ul>
  </nav>
  <div data-bs-spy="scroll" data-bs-target="#navbar-example2" data-bs-offset="0" tabindex="0">
  <h4 id="fat">@fat</h4>
  <p>...</p>
  <h4 id="mdo">@mdo</h4>
  <p>...</p>
  <h4 id="one">one</h4>
  <p>...</p>
  <h4 id="two">two</h4>
  <p>...</p>
  <h4 id="three">three</h4>
  <p>...</p>
  </div>
  

嵌套导航示例

滚动监控也适用于嵌套的.nav。如果嵌套.nav是.active,它的父层也会是.active状态。滚动导航条旁的块,并观察它的active变化。

Item 1

Placeholder content for the scrollspy example. This one relates to item 1. Takes you miles high, so high, 'cause she’s got that one international smile. There's a stranger in my bed, there's a pounding in my head. Oh, no. In another life I would make you stay. ‘Cause I, I’m capable of anything. Suiting up for my crowning battle. Used to steal your parents' liquor and climb to the roof. Tone, tan fit and ready, turn it up cause its gettin' heavy. Her love is like a drug. I guess that I forgot I had a choice.

Item 1-1

Placeholder content for the scrollspy example. This one relates to the item 1-1. You got the finest architecture. Passport stamps, she's cosmopolitan. Fine, fresh, fierce, we got it on lock. Never planned that one day I'd be losing you. She eats your heart out. Your kiss is cosmic, every move is magic. I mean the ones, I mean like she's the one. Greetings loved ones let's take a journey. Just own the night like the 4th of July! But you'd rather get wasted.

Item 1-2

Placeholder content for the scrollspy example. This one relates to the item 1-2. Her love is like a drug. All my girls vintage Chanel baby. Got a motel and built a fort out of sheets. 'Cause she's the muse and the artist. (This is how we do) So you wanna play with magic. So just be sure before you give it all to me. I'm walking, I'm walking on air (tonight). Skip the talk, heard it all, time to walk the walk. Catch her if you can. Stinging like a bee I earned my stripes.

Item 2

Placeholder content for the scrollspy example. This one relates to item 2. Don't need apologies. There is no fear now, let go and just be free, I will love you unconditionally. Last Friday night. Don't be a shy kinda guy I'll bet it's beautiful. Summer after high school when we first met. 'Cause she's the muse and the artist. What? Wait. No, no, no, no. Thought that I was the exception.

Item 3

Placeholder content for the scrollspy example. This one relates to item 3. Word on the street, you got somethin' to show me, me. All this money can't buy me a time machine. Make it like your birthday everyday. So we hit the boulevard. You make me feel like I'm livin' a teenage dream, the way you turn me on Skip the talk, heard it all, time to walk the walk. Word on the street, you got somethin' to show me, me. It's no big deal, it's no big deal, it's no big deal.

Item 3-1

Placeholder content for the scrollspy example. This one relates to item 3-1. Baby do you dare to do this? This is no big deal. Yeah, you're lucky if you're on her plane. Just own the night like the 4th of July! Standing on the frontline when the bombs start to fall. So just be sure before you give it all to me.

Item 3-2

Placeholder content for the scrollspy example. This one relates to item 3-2. You're original, cannot be replaced. All night they're playing, your song. California girls we're undeniable. Like a bird without a cage. There is no fear now, let go and just be free, I will love you unconditionally. I can see the writing on the wall. You could travel the world but nothing comes close to the golden coast.

<nav id="navbar-example3" class="navbar navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <nav class="nav nav-pills flex-column">
  <a class="nav-link" href="#item-1">Item 1</a>
  <nav class="nav nav-pills flex-column">
  <a class="nav-link ms-3 my-1" href="#item-1-1">Item 1-1</a>
  <a class="nav-link ms-3 my-1" href="#item-1-2">Item 1-2</a>
  </nav>
  <a class="nav-link" href="#item-2">Item 2</a>
  <a class="nav-link" href="#item-3">Item 3</a>
  <nav class="nav nav-pills flex-column">
  <a class="nav-link ms-3 my-1" href="#item-3-1">Item 3-1</a>
  <a class="nav-link ms-3 my-1" href="#item-3-2">Item 3-2</a>
  </nav>
  </nav>
  </nav>
  
  <div data-bs-spy="scroll" data-bs-target="#navbar-example3" data-bs-offset="0" tabindex="0">
  <h4 id="item-1">Item 1</h4>
  <p>...</p>
  <h5 id="item-1-1">Item 1-1</h5>
  <p>...</p>
  <h5 id="item-1-2">Item 1-2</h5>
  <p>...</p>
  <h4 id="item-2">Item 2</h4>
  <p>...</p>
  <h4 id="item-3">Item 3</h4>
  <p>...</p>
  <h5 id="item-3-1">Item 3-1</h5>
  <p>...</p>
  <h5 id="item-3-2">Item 3-2</h5>
  <p>...</p>
  </div>
  

列表组示例

滚动监控同样适用.list-group。滚动列表群组旁边的区域,并观察active class变化。

Item 1

Placeholder content for the scrollspy list-group example. This one relates to item 1. Don't need apologies. There is no fear now, let go and just be free, I will love you unconditionally. Last Friday night. Don't be a shy kinda guy I'll bet it's beautiful. Summer after high school when we first met. 'Cause she's the muse and the artist. What? Wait. Thought that I was the exception.

Item 2

Placeholder content for the scrollspy list-group example. This one relates to item 2. Yeah, she dances to her own beat. Oh, no. You could've been the greatest. 'Cause, baby, you're a firework. Maybe a reason why all the doors are closed. Open up your heart and just let it begin. So très chic, yeah, she's a classic.

Item 3

Placeholder content for the scrollspy list-group example. This one relates to item 3. We go higher and higher. Never one without the other, we made a pact. I'm walking on air. Someone said you had your tattoo removed. Now I’m floating like a butterfly. Tone, tan fit and ready, turn it up cause its gettin' heavy. Cause once you’re mine, once you’re mine. You just gotta ignite the light and let it shine! So we hit the boulevard. Do you ever feel, feel so paper thin. I see it all, I see it now.

Item 4

Placeholder content for the scrollspy list-group example. This one relates to item 4. Summer after high school when we first met. There is no fear now, let go and just be free, I will love you unconditionally. Sun-kissed skin so hot we'll melt your popsicle. This love will make you levitate.

<div id="list-example" class="list-group">
  <a class="list-group-item list-group-item-action" href="#list-item-1">Item 1</a>
  <a class="list-group-item list-group-item-action" href="#list-item-2">Item 2</a>
  <a class="list-group-item list-group-item-action" href="#list-item-3">Item 3</a>
  <a class="list-group-item list-group-item-action" href="#list-item-4">Item 4</a>
  </div>
  <div data-bs-spy="scroll" data-bs-target="#list-example" data-bs-offset="0" class="scrollspy-example" tabindex="0">
  <h4 id="list-item-1">Item 1</h4>
  <p>...</p>
  <h4 id="list-item-2">Item 2</h4>
  <p>...</p>
  <h4 id="list-item-3">Item 3</h4>
  <p>...</p>
  <h4 id="list-item-4">Item 4</h4>
  <p>...</p>
  </div>
  

用法

通过数据属性

要在您的导航条中加上滚动监控行为,只要将data-bs-spy=“scroll”加到您要监控的元素(通常是body)。接着将data-bs-target属性加入任何Bootstrap .nav元件的父元素ID或class。

body {
  position: relative;
  }
  
<body data-bs-spy="scroll" data-bs-target="#navbar-example">
  ...
  <div id="navbar-example">
  <ul class="nav nav-tabs" role="tablist">
  ...
  </ul>
  </div>
  ...
  </body>
  

通过JavaScript

在您的CSS加入position: relative;后,透过JavaScript调用滚动监控:

var scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '#navbar-example'
  })
  

必须有可解析的ID目标

导航连接并需有可解析的ID目标。举例来说:<a href="#home">home</a>必须确实对应到DOM中的<div id="home"></div>.

忽略不可见的目标元素

不可见的目标元素将被忽略,并和其对应的导航也不会有高亮显示效果。

方法

刷新

将滚动监控与新增或删除DOM元素一起使用时,您需要像这样调用refresh方法:

var dataSpyList = [].slice.call(document.querySelectorAll('[data-bs-spy="scroll"]'))
  dataSpyList.forEach(function (dataSpyEl) {
  bootstrap.ScrollSpy.getInstance(dataSpyEl)
  .refresh()
  })
  

注销

销毁元素上的滚动监控。(删除DOM元素上储存的数据)

获取实例

允许您取得滚动监控和DOM元素之间关联实体的静态方法。

var scrollSpyContentEl = document.getElementById('content')
  var scrollSpy = bootstrap.ScrollSpy.getInstance(scrollSpyContentEl) // Returns a Bootstrap scrollspy instance
  

选项

选项可以透过data属性或是JavaScript传递。像是data属性,增加选项名称到data-bs-,例如:data-bs-offset=“”.

Name Type Default Description
offset number 10 计算滚动监控的和顶部的偏移量
method string auto 查找监控元素所在的部分,auto将选择最好的方法来获得滚动坐标。offset将使用Element.getBoundingClientRect()方法来取得滚动坐标。position将会使用HTMLElement.offsetTop和HTMLElement.offsetLeft属性来取得滚动坐标。 Element.getBoundingClientRect() HTMLElement.offsetTop and HTMLElement.offsetLeft
target string | jQuery object | DOM element 指定特定元素套用滚动监控套件。

事件

Event type Description
activate.bs.scrollspy 每当一个新的元素启用滚动监控,这个事件会在监控元素上被触发。
var firstScrollSpyEl = document.querySelector('[data-bs-spy="scroll"]')
  firstScrollSpyEl.addEventListener('activate.bs.scrollspy', function () {
  // do something...
  })
  
返回顶部