1. 程式人生 > 實用技巧 >使用css來實現點選事件

使用css來實現點選事件

前段時間有人向我提過一個問題:“怎麼使用css實現點選操作。”

我想了下倒也不是不可以,在解答了之後覺得有趣,剛好最近也準備寫點部落格什麼的,便拿來做素材吧。

具體實現思路:在點選塊上新增一個隱藏的單選input,然後在css裡使用選擇器判斷當前選中塊。做出顯示或隱藏其他塊。整體程式碼如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head
> <body> <style> section{ margin-top:100px; margin-left: 100px; } .title{ font-size: 0;/* 清除盒模型之間的間隙 */ } .box{ display: inline-block; position
: relative; font-size: 18px; left:0; top:0; color:#b1b1b1; border-color: #b1b1b1; margin-right: 10px; border:1px solid #ccc; border-bottom: 0; line-height: 20px;
width:200px; text-align: center; border-top-right-radius: 10px; border-top-left-radius: 10px; } .box>input{ position: absolute; opacity: 0;/* 讓ie什麼的去死吧 */ width:100%; left:0; top:0; height:100%; z-index: 1; } .box>input:hover{ cursor:pointer; } .content{ display: none; text-align: left; color:#666; position: absolute; left:-1px; top:56px; border: 1px solid #ccc; padding:10px; width:414px; box-sizing: border-box; /* 方便計算寬度 */ border-bottom-right-radius: 10px; border-bottom-left-radius: 10px; } input[name=title]:checked+p{ /* 這裡是重點 */ color:#53d9ef; } input[name=title]:checked+p+div{ /* 這裡是重點 */ display: block; } .regression{ /* 畢竟是css,鬧著玩的嘛 */ margin-left: -212px; } </style> <section> <div class="title"> <div class="box"> <input type="radio" checked name="title" > <p>夏天的微風</p> <div class="content"> <p>夏天的風輕輕的吹過……</p> </div> </div> <div class="box"> <input type="radio" name="title" > <p>冬天的雪</p> <div class="content regression" > <p>雪下的那麼認真……</p> </div> </div> </div> </section> </body> </html>

重點程式碼:

input[name=title]:checked+p{ /*選擇器會玩就行~*         
    color:#53d9ef;
}
input[name=title]:checked+p+div{ /* 和上面一樣 */
    display: block;
}

以上就是這次分享的全部內容了;
第一篇文章,如寫的不好請指出。