2012-02-24 43 views
1

在下面的代碼中,我希望能夠將CSS樣式應用於父列表li class="parent"項目。但是,只有當用戶在該子女的子項li class="child"上懸停時纔會生效。在CSS中選擇一個孩子的父親

這是我的理解是,這將是不可能只使用CSS,但沒有人知道一個潛在的JavaScript解決方案的(理想情況下使用jQuery,因爲我們已經在使用我們的網站上這個庫)

謝謝!

<ul> 
    <li class="parent"><a href="URL" >Main Link</a> 
     <ul class="sub-menu"> 
      <li class="child"><a href="URL" >Link</a></li> 
     </ul> 
    </li> 
</ul> 
+0

請注意,雖然您已將'class =「parent」'放入您的標記中,但確實沒有理由這樣做。如下面的答案所示,使用'nearest('li')'查找最近的擁有物品。你甚至不需要'class =「child」',因爲你可以做'$('li li')。hover(...);' – Phrogz 2012-02-24 04:37:21

回答

2

一點都沒錯— CSS不允許您對DOM樹向上遍歷,只有向下。如在,你可以選擇孩子,但不是父母。

這裏有一個方法用jQuery做到這一點:

$("li.child").on("hover", function(){ 
    $(this) 
     .closest("li.parent") 
     .css({ 
      // styling here 
     }); 
}); 

我們做的是與類child選擇li元素。我們將hover事件綁定到它並在該事件發生時觸發一個函數。該函數找到子類li與類parent最接近的父親,並且我們更改其CSS。

更多關於on()hereclosest()herecss()here

另外請記住,對於早期版本的jQuery,您可以使用bind()delegate()

編輯:把它改變鼠標懸停鼠標移開:

$("li.child").on("mouseover mouseout", function(){ 
    $(this) 
     .closest("li.parent") 
     .toggleClass("myClass"); 
}); 

而你在這裏做什麼是你的CSS定義類myClasstoggleClass將添加該類,如果它尚不存在於該元素上並將其刪除。這是自我解釋。這樣,您可以節省幾個字節,並使用更受歡迎和推薦的jQuery。

+0

小的澄清:與CSS中相鄰的兄弟選擇器可以遍歷'向下'在源代碼中,但在DOM樹方面是「橫盤」的。 – Phrogz 2012-02-24 04:28:10

-1

使用jQuery的懸停爲此。

$(".child").hover(function(){ 
$(".parent").css() //check the jquery css api for the styling options 
}) 
+0

這將選擇整個DOM中的所有'.parent'元素。 – Phrogz 2012-02-24 04:28:59

+1

我假設只有一個班級叫他父母從他問什麼。答案沒有問題,只是過於籠統 – XepterX 2012-02-24 04:33:48

0

像這樣的東西應該工作:

//The hover method takes two functions, one it does on mouseover 
//and the other executes on mouseout 
​$(".child").hover(
    function(){//get the parent -> then get its parent (the li) 
     $(this).parent().parent().addClass("parent");//add the class to it 
    }, 
    function(){//this executes on mouseout 
     $(this).parent().parent().removeClass("parent"); 
    }//remove the class.. 
);​ 

您可以使用.parent類作爲標記和使用jQuery的class selector或者你可以使用一個variety of other selectors獲取對父母。

觀看演示:http://jsfiddle.net/D8zTE/1/

+1

檢查[this](http://api.jquery.com/closest/)了。 – Purag 2012-02-24 04:14:43

+0

的確如此,但我認爲他只想從孩子中選擇兩個級別,而不必關心它的類別。 – gideon 2012-02-26 08:24:07

2

你可以做這樣的事情:

$('li.child').hover(function() { 
    $(this).closest('.parent').addClass('red'); 
}, function() { 
    $(this).closest('.parent').removeClass('red');  
}); 

工作例如:

0
$("li.child").hover(function() { 
    $(this).parents('li.parent').addClass('parentHoverClass'); 
    //Alternatively, you could apply inline styles to the <li> like this: 
    //$(this).parents('li.parent').css({ 
    // 'display': 'block', 
    // 'color': '#FF00FF', 
    // 'text-decoration': 'underline' 
    //}); 
}, function() { 
    $(this).parents('li.parent').removeClass('parentHoverClass'); 
    //Or, you could reset inline styles to the <li> like this: 
    //$(this).parents('li.parent').css({ 
    // 'display': 'inline', 
    // 'color': '#00FF00', 
    // 'text-decoration': 'none' 
    //}); 
});