2011-12-02 92 views
0

divs按以下格式遞歸的jQuery選擇

<div class="box"> 
    <div class="button">B</div> 
</div> 
<div class="box"> 
    <div class="button">B</div> 
</div> 
<div class="box"> 
    <div class="button">B</div> 
</div> 

我要顯示的每個.button當他們的.box父徘徊。怎麼樣?

+0

請解釋爲什麼這必須使用jQuery做時CSS的設計爲這種情況的。 – kojiro

回答

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<style> 
.box {width: 30px; height:30px; margin:5px; display: block; float:left; cursor:default; font-size: 24px; font-weight:bold; padding: 5px; border: 1px #009 solid; background-color:#DFCCF4; text-align:center;} 
.button {display: none;} 
</style> 
<script> 
$(document).ready(function(e) { 
    $('.box').mouseover(function(){ 
     $('.button',this).show(); 
    }); 
    $('.box').mouseout(function(){ 
     $('.button',this).hide(); 
    }); 
}); 

</script> 
</head> 

<body> 

<div class="box"> 
    <div class="button">B</div> 
</div> 
<div class="box"> 
    <div class="button">B</div> 
</div> 
<div class="box"> 
    <div class="button">B</div> 
</div> 

</body> 
</html> 
+0

這部分是你需要的 - 雖然我已經發布了完整的例子。 。

+0

您也可以使用.hover()而不是mouseover和mouseout。 hover()需要2個函數,第一個函數在鼠標中調用,第二個函數在鼠標外面調用。它有點清潔,但它的確與上面完全一樣。 – Flater

+1

這是錯誤的;你需要輸入和離開。 – SLaks

5

只需使用CSS:

.box:hover .button { 
    display: block; 
} 
+0

當然,在上面我們需要'.box .button {display:none; }' –

+0

只需回答我問的問題。保持極限。你沒看到「JQuery」嗎? –

2

使用CSS:

.button { display: none; } 
.box:hover > .button { display: block; } 
+0

只需回答我問的問題。保持極限。你沒看到「JQuery」嗎? –

+0

在不解釋它的情況下設置限制是不合適的。 – kojiro

0

假設你不能使用:hover CSS僞選擇器(因爲它沒有對非錨元素在IE6的工作例如),那麼下面的工作:

CSS

.box .button { display: none; } 

jQuery的

$(".box").hover(
    function() { 
     $(".button", this).show(); 
    }, 
    function() { 
     $(".button", this).hide(); 
    } 
)