2016-06-14 60 views
0

我正在構建單頁設計網站,並想知道如何在滾動瀏覽ID時嚮導航菜單項添加課程。將ID addClass滾動到導航菜單以更改類別

我猜它會是這樣的:

if at ID-X addClass .active to menuitem-y 

在我的導航菜單我有價格的鏈接(鏈接www.example.com/#prices)。所以當我點擊價格時,它會平滑滾動到ID #prices。

所以可能應該是這樣的:

if "#prices" addClass(.active)->Menuitem-y 

我猜?

**更新** 感謝DaniP我有一些代碼在#prices到達時觸發警報。

var target = $("#prices").offset().top; 
var interval = setInterval(function() { 
    if ($(window).scrollTop() >= target) { 
     alert("made it!"); 
     clearInterval(interval); 
    } 
}, 250); 

我可以把CSS而不是警報?像#menuitem-y{color:#000;}

這個工程,但只有一個實例,什麼是最好的方式將此應用到更多的菜單項?

var target = $("#prices").offset().top; 
var interval = setInterval(function() { 
    if ($(window).scrollTop() >= target) { 
     $("#menu-item-16 a").addClass("active-prices"); 
     clearInterval(interval); 
    } 
}, 250); 
+0

你試過Bootstrap scrollspy了嗎? http://getbootstrap.com/javascript/#scrollspy –

+0

我沒有使用Bootstrap。我正在使用http://materializecss.com。它有一個滾動功能。 http://materializecss.com/scrollspy.html這可能會工作相同。我有一個去 – Steggie

+1

你嘗試過什麼嗎?至少搜索並嘗試與您的代碼http://stackoverflow.com/questions/7182342/how-to-detect-when-the-user-has-scrolled-to-a-certain-area-on-the-page-在你的頭銜中使用-jqu – DaniP

回答

1

我已經構建了一個jQuery插件,聽起來像它會爲你在這裏做什麼工作。

https://github.com/tferullo/eavesdrop

它增加了一個類到導航元素,因爲它對應於視圖中的元件。希望這可以幫助!

+0

編輯,對不起沒有看到示例文件夾!謝謝! – Steggie

+0

感謝這個腳本確實做了我想要的。但現在我必須在我的代碼中實現它。 我發現你的腳本中有一個錯誤,在我下載的文件中說: '; function'在開始時應該是'!function'根據你的演示頁面... – Steggie

+0

很高興它的工作。函數調用之前的分號是針對可能無法正確關閉的串聯腳本和/或其他插件的安全網。 – tfer77