nav分隔線 nav分隔線

聯成電腦網頁設計教學:純CSS手風琴效果

icon_fb icon_twitter icon_google
聯成電腦網頁設計教學:純CSS手風琴效果

文、前端小編

 

 

 

剛接觸CSS的你,對於Javascript還尚未有深刻的認識,要怎麼做出下面如圖所示的手風琴效果呢?

 

這個使用範圍相當廣又簡單方便的效果:手風琴效果,一般網站可以用在選單、產品分類,或是新聞公告…等等,就看網站開發者要怎麼運用。現在就跟著我們一步一步來完成吧!

 

要達成不用JS來完成這個效果,我們要使用label可以點選控制input[type=radio]這項特性,並且要注意label要對應到相對的input[type=radio]的id

	
		<body>
			<div class="accordion">
				<label for="tab1">1號</label>
				<div class="box">
					<input type="radio" name="tab" id="tab1">
				</div>
				<label for="tab2">2號</label>
				<div class="box">
					<input type="radio" name="tab" id="tab2">
				</div>
				<label for="tab3">3號</label>
				<div class="box">
					<input type="radio" name="tab" id="tab3">
				</div>
			</div>
		</body>
	

 

設定簡單的CSS,基本的CSS reset,body的背景有點顏色,這樣看得比較清楚。

	
	* {
		box-sizing : border-box;
	}
	body {
		margin : 0px;
		padding : 0px;
		background-color : #ecfaff;
	}
	.accordion  {
		width : 300px;
		margin : 80px auto 0;
	}
	

 

 

接下來稍微將label做的比較像按鈕的樣子。

	
	.accordion  label {
		display : block;
		width : 100%;
		text-align : center;
		border-radius : 5px;
		background-color : #ccc;
		margin-top : 10px;
		padding : 6px 12px;
		cursor : pointer;
	}
	

 

然後在每一個input[type=radio]後面新增一塊div,class命名為content,並且設定CSS。

	
		<body>
			<div class="accordion">
				<label for="tab1">1號</label>
				<div class="box">
					<input type="radio" name="tab" id="tab1">
					<div class="content">hello</div>
				</div>
				<label for="tab2">2號</label>
				<div class="box">
					<input type="radio" name="tab" id="tab2">
					<div class="content">hello</div>
				</div>
				<label for="tab3">3號</label>
				<div class="box">
					<input type="radio" name="tab" id="tab3">
					<div class="content">hello</div>
				</div>
			</div>
		</body>
	

 

	
	.content {
		height : 100px;
		background-color : #fff;
	}
	

 

 

再來,我們要使用這次重要的偽元素【:checked】與選擇器【+】【:checked】的功能為判定目前checkbox或radio是否有被選取,而【+】的功能是選擇緊鄰在後的下一個元素

下面範例的意思就是: 被選取的input[type=radio]的下一個 .content 背景變成橘色。

	
	input[type=radio]:checked + .content {
		background-color : #fa0;
	}
	

 

 

如果理解了上面偽元素與選擇器的功能,那我們就可以回來繼續做我們的手風琴!把 .content 元素的CSS再加點東西: 高度為0(height)、超出範圍要隱藏(overflow),另外加點轉場(transition)讓點選按鈕的動作不會那麼卡;再來讓被選取的radio後面 .content 的高度為100px。

	
	.content {
		height : 0px;
		background-color : #fff;
		overflow : hidden;
		transition : 0.5s;
	}
	input[type=radio]:checked + .content {
		height : 100px;
	}
	

 

最後再將input[type=radio]隱藏起來就大功告成了!

	
	input[type=radio] {
		display : none;
	}
	

 

 

這個簡單的效果提供給大家,在還沒有踏入Javascript的大門之前,就先使用吧,相信這些對於CSS初學者的你一定會有幫助的!

 

► 推薦課程:HTML5前端語法應用JavaScript網頁特效應用Dreamweaver網頁設計

 

 

 

 

痞客邦Blog:http://lccnetvip.pixnet.net/blog
FB粉絲團:https://www.facebook.com/lccnetzone
菜鳥救星:https://www.facebook.com/greensn0w

 

本網站使用相關網站技術以確保使用者獲得最佳體驗,通過使用我們的網站,您確認並同意本網站的隱私權政策。欲了解詳情,請參閱 隱私權政策