NavLink:悬停并处于活动状态的CSS动画

时间:2020-05-17 11:52:43

标签: javascript css reactjs

我正在尝试使用一些CSS设置nav-bar的样式,以向NavLinks添加一些动画。因此,我正在尝试实现将鼠标悬停在文本上时从右到左加下划线的功能,并且当NavLink处于活动状态时,我希望将其下划线。

通过我的解决方案,我几乎得到了我想要的行为,除了当NavLink处于活动状态时,悬停动画和活动的下划线不会彼此重叠。这两个下划线在文本下方形成两个单独的下划线。

Picture of current NavLink with hover and active

代码如下:

{navItems.map((item) => (
    <div className="example">
        <NavLink
            key={item.title.toLowerCase()}
            className="hover hover-1"
            activeClassName="active"
            to={item.link}
            exact={item.exact}
        >
            {item.title}
        </NavLink>
    </div>
))}

这是CSS:

@import "./../global";

$animate: all 0.2s ease-in-out;
$darkBlue: darkBlue;

.example {
  display: flex;
  flex-flow: row nowrap;
  align-items: bottom;
  margin: 0 0 5px;
  .hover {
    text-align: center;
    margin: 0 auto;
    padding: 0;
    transition: $animate;
    position: relative;
    &:before,
    &:after {
      content: "";
      position: absolute;
      bottom: 0px;
      width: 0px;
      height: 4px;
      margin: 5px 0 0;
      transition: $animate;
      transition-duration: 0.5s;
      opacity: 0;
      background-color: $darkBlue;
    }

    &.hover-1 {
      &:before,
      &:after {
        left: 0;
      }
    }
  }
  &:hover {
    cursor: pointer;
    .hover {
      &:before,
      &:after {
        width: 100%;
        opacity: 1;
      }
    }
  }
  .active {
      border-bottom: 4px solid $darkBlue;
  }
}

非常感谢您提供有关此问题的帮助:)

1 个答案:

答案 0 :(得分:0)

您可以通过在以下CSS中应用来实现您的要求。

.example {
 // remaining properties 

 // EVERYTHING IS SAME BUT JUST ADDED not
.hover:not(.active) {

text-align: center;
margin: 0 auto;
padding: 0;
transition: $animate;
position: relative;
&:before,
&:after {
  content: "";
  position: absolute;
  bottom: 0px;
  width: 0px;
  height: 4px;
  margin: 5px 0 0;
  transition: $animate;
  transition-duration: 0.5s;
  opacity: 0;
  background-color: $darkBlue;
}

&.hover-1 {
  &:before,
  &:after {
    left: 0;
  }
 }
}
 // remaining properties
}