[英]Adding active class to menu when section changes
當我滾動頁面時,我想添加 class 活動菜單項。 我可以像這樣獲取當前的 div id var currSection = $(this).attr('id')。 我堅持 id 和 data-id 匹配。 這是代碼。 TY 幫助家伙。
$(document).scroll(function() { var cutoff = $(window).scrollTop(); $('div').each(function(){ if($(this).offset().top + $(this).height() > cutoff){ $('div').removeClass('current'); $(this).addClass('current'); var currSection = $(this).attr('id'); console.log(currSection); if ($('.circle li').data('id') == currSection) { }; return false; } }); });
ul{ position:fixed; z-index:9; top:0; }.active{ color:red; } div{ height:500px; } div:nth-child(odd){ background:green; } div:nth-child(even){ background:blue; }
<div id="home"></div> <div id="who"></div> <div id="team"></div> <div id="why"></div> <div id="contact"></div> <ul class="circle"> <li data-id="home" class="active">a</li> <li data-id="who">b</li> <li data-id="team">c</li> <li data-id="why">d</li> <li data-id="contact">f</li> </ul>
將滾動事件偵聽器更改為此
$(document).scroll(function () {
var cutoff = $(window).scrollTop();
$('div').each(function () {
if ($(this).offset().top + $(this).height() > cutoff) {
$('div').removeClass('current');
$(this).addClass('current');
var currSection = $(this).attr('id');
console.log(currSection);
$('li').removeClass('active');
$('li[data-id=' + currSection + ']').addClass('active');
return false;
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.