在作網頁時,咱們常常能夠碰到banner圖的切換。對於那些JS薄弱的同窗來講,這就很尷尬了。今天,我來告訴你們如何使用CSS作出banner圖切換的效果。app
這裏,用到了lable標籤與input的組合,首先先來了解下lable標籤佈局
<label> 標籤爲 input 元素定義標籤(label)。spa
label 元素不會向用戶呈現任何特殊的樣式。不過,它爲鼠標用戶改善了可用性,由於若是用戶點擊 label 元素內的文本,則會切換到控件自己。code
<label> 標籤的 for 屬性應該等於相關元素的 id 元素,以便將它們捆綁起來。blog
input標籤有個checked屬性,當lable屬性綁定後,選中lable便可選中input標籤圖片
首先,先作一個基本的HTML佈局ci
<div class="main"> <input type="radio" name="p" id="name1" class="set_page1"/> <input type="radio" name="p" id="name2" class="set_page2"/> <input type="radio" name="p" id="name3" class="set_page3"/> <input type="radio" name="p" id="name4" class="set_page4"/> <input type="radio" name="p" id="name5" class="set_page5"/> <!--lable中的for須要綁定對應的input的id--> <label for="name1" class="c1"></label> <label for="name2" class="c2"></label> <label for="name3" class="c3"></label> <label for="name4" class="c4"></label> <label for="name5" class="c5"></label> <div class="photo"> <ul> <li class="li1"> <img src="img/green-tea-cream-frappuccino-20151022185851.jpeg"/> </li> <li> <img src="img/hot-caramel-macchiato-20151022185811.jpg"/> </li> <li> <img src="img/hot-green-tea-latte-20160819155511.jpg"/> </li> <li> <img src="img/Starbucks-Hazelnut-Latte-20150924183645.jpg"/> </li> <li> <img src="img/starbucks-flatwhite-20151026112356.jpg"/> </li> </ul> </div> </div>
for綁定input的ID實現lable與input的綁定input
加以修飾it
label{ cursor: pointer; display: inline-block; opacity: 0.3; height: 70px; width: 70px; margin-top: 100px; background-color: red; } label:hover{ opacity: 1; } input{ display:none; } ul{ list-style: none; padding: 0px; height: 365px; overflow: hidden; margin-left: 480px; position: relative; }
.set_page1:checked ~.photo ul li:nth-child(1){ position: absolute; top: 0px; z-index: 25; } .set_page2:checked ~.photo ul li:nth-child(2){ position: absolute; top: 0; z-index: 22; } .set_page3:checked ~.photo ul li:nth-child(3){ position: absolute; top: 0; z-index: 23; } .set_page4:checked ~.photo ul li:nth-child(4){ position: absolute; top: 0; z-index: 24; } .set_page5:checked ~.photo ul li:nth-child(5){ position: absolute; top: 0; }
隱藏input,由於這裏咱們只需用到input的checked屬性。選中lable時,與之綁定的Input也會處於checked狀態,這樣,咱們只需利用checked屬性加上僞類選擇器。就能夠實現banner圖的切換。因爲定位的緣由,會使後面的圖蓋住前面的圖,因此須要設置z-index使圖片上去.io
對lable稍加修飾,就能夠拿去網頁上用了,不用複雜的JS代碼啦(ps:對lable修飾時,須要設置display:block屬性)。