---
# System prepended metadata

title: '[Bootstrap] 監測滾動條 ScrollSpy'
tags: [Bootstrap]

---

# [Bootstrap] 監測滾動條 ScrollSpy

###### tags: `Bootstrap`

網頁裡的文字過多便可使用scrollspy以提升使用者瀏覽的便利性，當我們點選上方的選單項目，頁面會自動跳轉到該區塊，選單項目同時也會自動反白，為達此效果便可使用ScrollSpy語法。


![](https://i.imgur.com/XMNSJOa.png)

* 在每個選單項目上設定id，並在menu裡的項目中的href目標位置為區塊id
* 並可使用jquery增加scroller效果


---

### **實作方式**

1. 在body標籤中新增id


```
<body data-spy="scroll" data-target="#main-nav" id="home">

```

2. menu中的item使用`<a>`標籤，並將href設定為目標section的#id

```
<li class="nav-item">
  <a href="#home-section" class="nav-link">Home</a>
</li>
<li class="nav-item"></li>
 <a href="#mission-head-section" class="nav-link">Mission</a>
</li>
<li class="nav-item">
  <a href="#teams-head-section" class="nav-link">Team</a>
</li>
<li class="nav-item">
  <a href="#advantage-head-section" class="nav-link">Advantage</a>
</li>
```

3. 用jQuery初始化scrollspy即可完成跳轉

```
$('body').scrollspy({ target:'#main-nav'});

```
4. 若要調整滑動速度，添加以下語法便可設定移動的速度
```
        $('#main-nav a').on('click',function(event){
            if(this.hash !==""){
                event.preventDefault();
                const hash = this.hash;
                $('html,body').animate({
                    scrollTop: $(hash).offset().top
                },1000, function(){
                    window.location.hash = hash;
                })
            }
        })
```



