代碼
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#menu{
width: 300px;
}
div a{
float: left;
display: none;
width: 300px;
background-color: #888;
}
.has_children{
background-color: #555;
color: #fff;
cursor: pointer;
}
.highlight{
background-color: green;
}
</style>
<title>鏈式寫法</title>
</head>
<body>
<div id="menu">
<div class="has_children">
<span>第1章</span>
<a href="#">1.1</a>
<a href="#">1.2</a>
<a href="#">1.3</a>
<a href="#">1.4</a>
<a href="#">1.5</a>
</div>
<div class="has_children">
<span>第2章</span>
<a href="#">2.1</a>
<a href="#">2.2</a>
<a href="#">2.3</a>
<a href="#">2.4</a>
<a href="#">2.5</a>
</div>
<div class="has_children">
<span>第3章</span>
<a href="#">3.1</a>
<a href="#">3.2</a>
<a href="#">3.3</a>
<a href="#">3.4</a>
<a href="#">3.5</a>
</div>
</div>
</body>
<script src="../scripts/jquery-3.2.1.js"></script>
<script type="text/javascript">
$(".has_children").on('click', function(){
$(this).addClass('highlight')
.children('a').show()
.end()
.siblings().removeClass("highlight")
.children('a').hide();
});
</script>
</html>
在這次練習中螃诅,遇到了兩個問題:
1坤次、為什么當點擊div.has_children時,添加了highlight樣式支子,但只有<span>標簽的背景色變?yōu)榱司G色。下面展開的a標簽的內(nèi)容的背景色并沒有變?yōu)榫G色达舒。a標簽中的內(nèi)容也是div.has_children中的內(nèi)容值朋。
2、在調(diào)用了siblings()方法后巩搏,下面的.children('a').hide(); 作用于this還是this的兄弟元素昨登。
第一個問題:因為a標簽設(shè)置了float樣式,此時已經(jīng)脫離了文檔流贯底,而div.has_children并沒有設(shè)置高度丰辣,因此div中包裹著的是span標簽撒强。如果要在視覺上div.has_children包裹a標簽◇鲜玻可以動態(tài)地給div.has_children添加高度飘哨。但是此時的a標簽其實還是脫離了文檔流了的。
第二個問題:在調(diào)用siblings后琐凭,后面的.children('a').hide();雖然還跟在$(this)后面芽隆,但是收到siblings()的影響。.children('a').hide();此時是作用于this對象的兄弟元素统屈。
其中這里面還有另一個知識點胚吁。
點擊了div.has_children后,a標簽一個一個往下排列愁憔。而沒有一個一個挨著左邊排列腕扶。這是因為a標簽設(shè)置了float樣式,然后就可以設(shè)置寬度吨掌,此時設(shè)置的寬度和父元素div.menu的寬度是一樣的半抱。所以就會外下排列。
上述純屬個人理解膜宋,如有不正確的地方窿侈,請指正。