假設有個菜單
active 是使用者正在這個 div 位子的顏色
<a class="section-btn active ease-in-out" href="#section-2">服務介紹</a>
<a class="section-btn ease-in-out" href="#section-3">成功案例</a>
<a class="section-btn ease-in-out" href="#section-4">聯絡我們</a>
菜單點擊後到該 section
另外移除所有 active 並為自己加上 active 這沒問題
$('.section-btn').on('click', function() {
$('.section-btn').removeClass('active');
$(this).addClass('active');
$('body, html').animate({
scrollTop: $($(this).attr('href')).offset().top - 70
}, 1000);
});
每一個 section
<div id="section-2">
</div>
<div id="section-3">
</div>
<div id="section-4">
</div>
只是現在有個實現我想不到
就是當使用者是用捲軸往上回去時,此時會經過其他 section
怎麼樣讓對應的菜單能夠針對該菜單加上 active? 讓使用者知道自己現在在哪個 section?
喔喔對,這樣的概念@@
只是有更輕盈的方式嗎?
codepen 有修改了 你再看看
輕盈是??
position().top
這個是可以算該 div 到頂的距離對吧
只是我是要讓 section-btn
加入 active
當經過該 div 時
position().top是用來偵測
該DIV 最上方
了解
if ( scroll >= $('#section-2').position().top &&
scroll < $('#section-3').position().top)
{
$('.section-btn:nth-child(0)').addClass('active');
}
else {
$('.section-btn:nth-child(0)').removeClass('active');
}
if ( scroll >= $('#section-3').position().top &&
scroll < $('#section-4').position().top)
{
$('.section-btn:nth-child(1)').addClass('active');
}
else {
$('.section-btn:nth-child(1)').removeClass('active');
}
if ( scroll >= $('#section-4').position().top)
{
$('.section-btn:nth-child(2)').addClass('active');
}
else {
$('.section-btn:nth-child(2)').removeClass('active');
}
把裡面改成這樣?
大概寫出來了,只是好像有點衝突
我最下面 section-4 內容不多,所以很難碰到上方 top,然後也沒有 section-5 ,所以按鈕那邊會壞掉
if (scroll >= $('#section-1').position().top && scroll < $('#section-2').position().top) {
$('.section-btn:nth-child(1)').addClass('active');
} else {
$('.section-btn:nth-child(1)').removeClass('active');
}
if (scroll >= $('#section-2').position().top && scroll < $('#section-3').position().top) {
$('.section-btn:nth-child(2)').addClass('active');
} else {
$('.section-btn:nth-child(2)').removeClass('active');
}
if (scroll >= $('#section-3').position().top && scroll < $('#section-4').position().top) {
$('.section-btn:nth-child(3)').addClass('active');
} else {
$('.section-btn:nth-child(3)').removeClass('active');
}
優化的寫法參考:
把id名(或calss名)&對應的position().top用陣列記錄下來,
每次滾動就去foreach這個陣列,
判斷當前的scrollTop 是否有在陣列範圍內,
有則addClass,無則removeClass,
這樣可以只寫一個條件判斷搞定,
不然如果section-id很多(例如infiniteScroll產生的section)
不就要把if寫到天荒地老...
優化就交給樓主動動腦了...加油~
好的感謝
資料不多觸發不到的話可以用下面的語法來調整
if ( scroll >= $('#section-4').position().top - 300)
{
$('.section-btn:nth-child(3)').addClass('active');
}
else {
$('.section-btn:nth-child(3)').removeClass('active');
}
-300 它的觸發點就會往上跑