利用transition属性实现一个简单小巧的hover效果

来源:互联网 发布:李兴华 java 框架 编辑:程序博客网 时间:2024/06/06 02:52

在实际工作中,简单利用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

(完)

原创粉丝点击