2017-07-01 10 views
0

私は、ホバーでスタイリングしている各アンカータグに空のdivを持つナビゲーションを持っています。javascript経由でスクロールにCSSクラスを追加する

HTML

<li><a href="#events">SPECIAL EVENTS <div></div></a></li> 

CSS

a:hover div, a:active div{ 
    color: $black; 
    height: 1px; 
    background-color: $black; 
    width: 100%; 
    margin-top: 5px; 
} 

はまた、私はいくつかのJSをクリックの上に取り付けていますアクティブなクラスを持っています。これは現在正しく動作しています。

var currentDiv; 

function addSelected(){ 

if(currentDiv !== undefined){ 
    $(currentDiv).removeClass("active");  
} 

currentDiv = $(this).find('div'); 
$(currentDiv).addClass("active"); 
} 

$(".menu a").click(addSelected); 

私がやっていることは、ユーザーのスクロールに基づいて同じアクティブなクラスが添付されていることです。私はそのほとんどを動作させていますが、アンカーそのものではなく、divをどのようにしてdivに接続するかを理解できないようです。ここに私が働いているjsがあります。

JS

// Cache selectors 
var lastId, 
topMenu = $("#desktop-nav"), 
topMenuHeight = topMenu.outerHeight()+15, 
// All list items 
menuItems = topMenu.find("a"), 
// Anchors corresponding to menu items 
scrollItems = menuItems.map(function(){ 
    var item = $($(this).attr("href")); 
    if (item.length) { return item; } 
}); 

// Bind to scroll 
$(window).scroll(function(){ 
// Get container scroll position 
var fromTop = $(this).scrollTop()+topMenuHeight; 

// Get id of current scroll item 
var cur = scrollItems.map(function(){ 
if ($(this).offset().top < fromTop){ 
    return this; 
} 
}); 
// Get the id of the current element 
cur = cur[cur.length-1]; 
var id = cur && cur.length ? cur[0].id : ""; 

if (lastId !== id) { 
    lastId = id; 
    // Set/remove active class 
    menuItems 

    //.parent().removeClass("active") 
    //.end().filter("[href='#"+id+"']").parent().addClass("active"); 

    .removeClass("active"); 
    end().filter($("[href='#"+id+"']")).find('div').addClass("active"); 

    console.log(id); 
}     
}); 

私は変更しようとしています一部は、この

"[href='#"+id+"']").parent() 

だと思いますが、私がしようと、すべてが仕事や私にエラーを与えていないのいずれかです。ここで

EDIT

は私が修正しようとしていますフィドルです。

fiddle link

+0

あなたの現在の状況はどうあります。あなたはフィドルを提供できますか? –

+0

アンカーの内側にあるdivタグではなく、アンカータグの親にクラスをアタッチしています – icekomo

+0

スタックされた場所に完全なコードを入力してください。 –

答えて

1

利用children()の代わりに、parent()またはfind()

例:

if (lastId !== id) { 
     lastId = id; 
     // add/remove active class on div 
     menuItems 
     .children().removeClass("active") 
     .end().filter("[href='#"+id+"']").children().addClass("active"); 
    } 
1

あなたのクリックハンドラのように)(これは、検索を使用するように変更してみてください:

"[href='#"+id+"']").find('div') 
+0

これは最初のものを見つけたようですが、この '.end()。filter(" [href = '# "+ id +"'] ")にコードを更新しても、 ( 'div')。addClass( "active"); ' – icekomo

0

私はあなたが試したと仮定...

"[href='#"+id+"']").parent().find('div') 

および/または。 ..

"[href='#"+id+"'].div" 

...もしそうなら、classまたはiddivに追加してそのようにターゲティングできますか?

+0

はい私はdivにクラスを追加できますが、上記のコードでどのようにクラスをターゲットにするのかはまだ分かりません。 – icekomo

関連する問題