[英]dynamic table of content using jquery
我試圖通過添加一個名為“ active”的類在頁面上創建固定的目錄表,以突出顯示哪些元素在頁面上可見,我的html如下所示:
<div id="table_of_content">
<a class="essay_intro" href="#">Intro</a>
<a class="essay_body" href="#">Body</a>
<a class="essay_conclusion" href="#">Conclusion</a>
</div>
<div class="dircontent" id="essay_intro">
</div>
<div class="dircontent" id="essay_body">
</div>
<div class="dircontent" id="essay_conclusion">
</div>
我的JavaScript如下所示:
$(document).ready(function() {
$(window).scroll( function(){
$('.dircontent').each( function(i){
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var top_of_object = $(this).offset().top;
var bottom_of_window = $(window).scrollTop() + $(window).height();
var top_of_window = $(window).scrollTop();
var id_of_object = this.id;
if( bottom_of_window > top_of_object && top_of_window < bottom_of_object){
$("."+id_of_object).attr('class', 'active');
}else{
$("."+id_of_object).removeClass('active');
}
});
})});
目前,一旦我開始滾動,代碼便會觸發,並且永不消失。 活動類永遠不會從頁面上不可見的元素中刪除。 我怎樣才能解決這個問題? 有沒有比這個更好的解決方案來向用戶顯示他們在頁面上的位置了? 我在尋找一個比插件簡單的代碼。
只需更換
$("."+id_of_object).attr('class', 'active');
同
$("."+id_of_object).addClass('active');
使用attr
時要刪除類id_of_object
,因此$("."+id_of_object)
不再找到您的對象。
jQuery帶有.addClass("classname")
函數,因此在處理類時使用它而不是.attr()
。 另外,在每個循環之前,輸入:
$(".active").removeClass("active");
然后從if語句中刪除else子句。 在您的if語句中,使用:
$(this).addClass("active");
您正在使用類,因此jQuery將選擇具有該名稱的所有類,因此無論何時您運行$("."+id_of_object).removeClass("active");
具有相同類名的任何元素都將刪除其活動類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.