利用transition屬性實現一個簡單小巧的hover效果

在實際工作中,簡單利用css3的屬性可以讓頁面更生動,如下面的例子:

這裏寫圖片描述

“瞭解詳情”的hover效果比單純的顏色變換效果更生動。而實現的方式就是簡單的利用了css3transition屬性。

頁面代碼結構如下:

<div class="box">
    <a href="#">
        <span>瞭解詳情</span>
        <em></em>
    </a>
</div>

原理

  1. 定位一個 初始width爲0的em元素,hover的時候再將 width設置爲容器的width.
  2. 再利用transiton對width變化的過程設置過度效果

css如下:

.box a {        
    position: relative; 
    z-index: 0;
    display: inline-block;
    width: 158px;
    height: 38px;
    line-height: 38px;
    text-align: center;
    color: #fff;
    border: 1px solid #fff;
    border-radius: 20px;
}
.box a em {
    position: absolute;
    z-index: -1;
    top: 0px;
    left: 0px;
    display: inline-block;
    width: 0;  
    height: 100%;
    background-color: #fff;
    border-radius: 20px;
    transition: width .3s ease;
}

.box a:hover span {
    color: #00aeff;
}

.box a:hover em {
    width: 100%;  
}

利用僞元素可以讓代碼更簡潔,語義化,代碼如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" type="text/css" href="css/common.css"/>
        <style>
            .box {
                height: 500px;
                background-color: #4FAEE0;
            }
            .box a {        
                position: relative; 
                z-index: 0;
                display: inline-block;
                width: 158px;
                height: 38px;
                line-height: 38px;
                text-align: center;
                color: #fff;
                border: 1px solid #fff;
                border-radius: 20px;
            }
            .box a:after {
                content: '';
                position: absolute;
                z-index: -1;
                top: 0px;
                left: 0px;
                display: inline-block;
                width: 0;  
                height: 100%;
                background-color: #fff;
                border-radius: 20px;
                -moz-transition: width .3s ease;
                -webkit-transition: width .3s ease;
                -o-transition: width .3s ease;
                transition: width .3s ease;
            }
            .box a:hover {
                color: #00aeff;
            }
            .box a:hover:after {
                width: 100%;  
            }
        </style>
    </head>
    <body>
        <div class="box">
            <a href="#">瞭解詳情</a>
        </div>
    </body>
</html>

參考

  1. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions
  2. https://developer.mozilla.org/en-US/docs/Web/CSS/transition

(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章