链接下划线是非常常见的一种样式,最近做了一个非常简单的视觉效果,非常不错,完整代码查看。

XML/HTML Code 复制内容到剪贴板 <!DOCTYPE html>   < html >    < head >       < meta   charset = "gb2312" >       < meta   name = "viewport"   content = "width=device-width" >       < title > JS Bin </ title >    < style >    body{      background-color: #000;    }       h2{       text-align: center;      margin-top: 100px;    }       h2  >  a {      position: relative;      color: #FFF;      text-decoration: none;      padding-bottom: 5px;    }       h2  >  a:hover {      color: #FFF;    }        h2  >  a:before {      content: "";      position: absolute;      width: 100%;      height: 2px;      bottom: 0;      left: 0;      background-color: #FFF;      visibility: hidden;      -webkit-transform: scaleX(0);      transform: scaleX(0);      -webkit-transition: all 0.3s ease-in-out 0s;      transition: all 0.3s ease-in-out 0s;    }       h2  >  a:hover:before {      visibility: visible;      -webkit-transform: scaleX(1);      transform: scaleX(1);    }    </ style >    </ head >    < body >        < h2 >          < a   href = "/" > 悬停在我上面 </ a >        </ h2 >    </ body >    </ html >      

创建这种效果是非常简单的,不需要添加额外的DOM元素到HTML,不过需要考虑一下浏览器的兼容性问题,在老旧版本的浏览器中它只会显示为一个普通的下划线。

好了,现在正式开始。我们需要做的第一件事就是去除text-decoration,并设置链接为相对定位。我们需要确保链接在hover时不会改变颜色,这里我们拿h2举例:

CSS Code 复制内容到剪贴板 h2 > a {           position relative ;           color #000 ;           text-decoration none ;    }       h2 > a:hover {           color #000 ;    }          

接下来,我们要添加border,通过变换隐藏它。插入一个:before并且设置它scaleX(0),保守起见,如果浏览器不支持,我们通过visibility: hidden隐藏它。

CSS Code 复制内容到剪贴板 h2 > a:before {           content "" ;           position absolute ;           width : 100%;           height 2px ;           bottom bottom : 0;           left : 0;           background-color #000 ;           visibility hidden ;          -webkit-transform: scaleX(0);          transform: scaleX(0);          -webkit-transition:  all  0.3s ease-in-out 0s;          transition:  all  0.3s ease-in-out 0s;    }      

最后设置动画时间为0.3s,现在我们只需要设置元素在hover时显示并且scaleX(1):

CSS Code 复制内容到剪贴板 h2 > a:hover:before {           visibility visible ;          -webkit-transform: scaleX(1);          transform: scaleX(1);    }  

大功告成!

这样就完成了一个很有活力的下划线动画。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。