如何实现将效果悬停在React Router Link上以显示下划线的过渡效果?

时间:2018-08-07 05:27:58

标签: javascript css reactjs react-router-dom

我在我的react项目中使用react-router-dom节点包来实现路由。

设置路由器链接后,默认情况下,我使用以下自定义CSS隐藏链接下划线:

let styles = theme => ({
   TextLink: {
      position: 'relative',
      color: 'white',
      textDecoration: 'none',    
      '&:hover':{
            color: 'white',
      },
});

使用此功能,我得以隐藏。

我的目标是创建一个在悬停时显示下划线并具有过渡效果的链接(链接下划线从中心到两端增长)。

修改后的CSS或代码示例以及任何其他节点程序包将很有帮助。

2 个答案:

答案 0 :(得分:1)

以下示例是在纯CSS中完成的。

reactjs中的链接基本上是a标记,因此您可以使用以下CSS

@import url("https://fonts.googleapis.com/css?family=Montserrat:500");
body {
  font-family: 'Montserrat', sans-serif;
}

ol,
ul {
  list-style: none;
}

li {
  display: inline-block;
  padding: 20px 0 20px;
}

a {
  text-decoration: none;
  position: relative;
  display: block;
  padding: 16px 0;
  margin: 0 12px;
  font-size: 1.2rem;
  text-transform: uppercase;
  transition: color 0.1s, background-color 0.1s;
  color: #000;
}
a:hover {
  color: #4dd0e1;
}
a:focus, a:active {
  color: #00bcd4;
}

a::before {
  content: '';
  display: block;
  position: absolute;
  top: 100%;
  height: 3px;
  width: 100%;
  background-color: #00bcd4;
  -webkit-transform-origin: center top;
          transform-origin: center top;
  -webkit-transform: scale(0, 1);
          transform: scale(0, 1);
  transition: color 0.1s, -webkit-transform 0.2s ease-out;
  transition: color 0.1s, transform 0.2s ease-out;
  transition: color 0.1s, transform 0.2s ease-out, -webkit-transform 0.2s ease-out;
}

a:active::before {
  background-color: #00bcd4;
}

a:hover::before,
a:focus::before {
  -webkit-transform-origin: center top;
          transform-origin: center top;
  -webkit-transform: scale(1, 1);
          transform: scale(1, 1);
}
<nav>
  <ul>
    <li class=""><a href="#">home</a></li>
    <li class=""><a href="#">career</a></li>
    <li class=""><a href="#">projects</a></li>
    <li class=""><a href="#">about us</a></li>
    <li class=""><a href="#">contact us</a></li>
  </ul>
</nav>

答案 1 :(得分:1)

如果给<a>的显示声明为inline-block,则可以对其应用::after伪元素。可以使伪元素具有动态功能,代替传统的下划线。

您可以首先将伪元素放置在中心(使用position: absolute; left: 50%;),并通过将其宽度设置为0使其不可见。

<a>悬停后,可以将伪元素的位置更新为left: 0;,并将其宽度设置为100%

如果同时设置这两个值的动画,则伪元素似乎会从中心向外增长,直到变成全角下划线为止。

工作示例:

a {
position: relative;
display: inline-block;
font-size: 16px;
line-height: 24px;
height: 24px;
color: rgb(0, 0, 191);
text-decoration: none;
}

a::after {
content: '';
position: absolute;
display: block;
bottom: 0;
left: 50%;
width: 0;
height: 2px;
border-bottom: 2px solid rgb(255, 0, 0);
}

a, a::after {
transition: all 0.6s linear;
}

a:hover {
color: rgb(255, 0, 0);
}

a:hover::after {
left: 0;
width: 100%;
}
<a href="">Hover Me</a>