首页 > 解决方案 > NavLink:悬停和活动时的 CSS 动画

问题描述

我正在尝试nav-bar使用一些 CSS 设置样式,以向 NavLinks 添加一些动画。所以我试图在悬停时实现这一点,文本将从右到左加下划线,当 NavLink 处于活动状态时,我希望它加下划线。

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

当前 NavLink 的图片,悬停并处于活动状态

这是代码:

{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;
  }
}

我非常感谢您对这个问题的帮助:)

标签: javascriptcssreactjs

解决方案


您可以通过在下面的 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
}

推荐阅读