react router Link悬停显示下划线的过渡效果如何实现?

How to implement transition effect for displaying underline on hovering a react router Link?

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

设置路由器 links 后,我使用以下自定义 CSS 默认隐藏 link 下划线:

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

使用这个我可以隐藏。

我的objective是做一个link悬停时显示下划线的过渡效果(Link下划线从中心向两端增长)。

修改后的 CSS 或包含任何其他节点包的代码示例会有所帮助。

下面的例子是纯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>

如果您给 <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>