天天看點

純css實作切換标簽效果

純css實作切換标簽效果

一.首先上demo

純css實作切換标簽效果

如圖所示:點選第一個按鈕顯示按鈕樣式改變,彈出第一個界面;點選第二個按鈕改變按鈕樣式,彈出第二個界面,實作的主要方式要看我們對input的了解程度

二.實作原理

1.首先建立div,為div添加寬高,設定div為相對定位的元素

2.建立兩個type為radio的input,給兩個input一個相同name,讓它和同級的lable綁定,注意input要display:none掉,因為input即使沒有了位置,但是它的點選事件依舊存在于label内,此時的label具備了input的所有特性,且可以改變樣式

純css實作切換标簽效果

3.設定label的點選事件checked

我已經預設給了第一個按鈕checked

純css實作切換标簽效果

設定點選事件 使用input:checked+label

純css實作切換标簽效果

4.建立兩個div,在設定相對定位的div之下(父子關系)或者和input同級關系,這兩個div設定絕對定位,設定樣式,然後 visibility: hidden,再通過checked讓這倆個div顯示

純css實作切換标簽效果

總結:想使用css來做點選事件,a與iframe當然也可以實作,但是a不能做到點選後的樣式改變,另一個恢複預設樣式,熟練使用input可以實作很多簡單的邏輯效果,例如輪播圖,一個界面内切換标簽等

下面放源碼:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=
    , initial-scale=1.0">
    <title>純css實作切換标簽效果</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        main {
            width: 600px;
            height: 600px;
            background-color: violet;
        }

        .demo {
            width: 100%;
            height: 100%;
            position: relative;

        }

        input {
            display: none;

        }

        #check_first+label,
        #check_second+label {
            display: inline-block;
            width: 100px;
            height: 60px;
            line-height: 60px;
            text-align: center;
            border: 1px solid;
            background-color: white;
            color: black;
            float: left;
        }
        #check_second+label {
            float: right;
        }

        #check_first:checked+label,
        #check_second:checked+label {
            background-color: black;
            color: white;

        }
        .window_first,
        .window_second{
            position: absolute;
            width: 400px;
            height: 200px;
            background-color: white;
            top: 100px;
            left: 100px;
            visibility: hidden;
        }
        .window_second{
            background-color: tomato;
        }
        #check_first:checked~.window_first,
        #check_second:checked~.window_second{
            visibility: visible;
            transform: scale(1.2);
            transition: all .3s ease;
        }
        
    </style>
</head>

<body>
    <main>
        <div class="demo">
            <input type="radio" name="bt" id="check_first" checked>
            <label for="check_first">按鈕1</label>
            <input type="radio" name="bt" id="check_second">
            <label for="check_second">按鈕2</label>
            <div class="window_first">這是第一個界面</div>
            <div class="window_second">這是第二個界面</div>
        </div>

    </main>
</body>

</html>
           

繼續閱讀