【问题标题】:how to change underline color on active link - react如何更改活动链接上的下划线颜色 - 反应
【发布时间】:2020-10-03 13:22:24
【问题描述】:

我有一些逻辑来为 React 中的活动链接设置样式,并且我有 CSS 用于导航链接上的动画下划线。问题是我不知道如何在链接处于活动状态时更改下划线的颜色。

在 CSS 中,我认为选择器应该是 .nav-link:after:active

如何在链接处于活动状态时更改下划线的颜色?

const isActive = (history, path) => {
  if (history.location.pathname === path) {
    return { color: "#ff7315" };
  } else {
    return { color: "#232020" };
  }
};

styles.css

  .nav-item { 
    display: table-cell; 
    position: relative; 
    padding: 15px 0;
  }
  .nav-link {
    display: inline-block;
    position: relative;
  }
  .nav-link:after {    
    background: none repeat scroll 0 0 transparent;
    bottom: 0;
    content: "";
    display: block;
    height: 2px;
    left: 50%;
    position: absolute;
    background: #3a3535;
    transition: width 0.3s ease 0s, left 0.3s ease 0s;
    width: 0;
  }

  .nav-link:hover:after { 
    width: 100%; 
    left: 0; 
  }

【问题讨论】:

    标签: css reactjs


    【解决方案1】:

    你可以用你提供的那个来做这样的事情。

    .nav-item {
      position: relative;
      padding: 15px 0;
    }
    
    .nav-link {
      display: inline-block;
      position: relative;
      text-decoration: none;
      color: #000;
    }
    
    .nav-link.active {
      color: blue
    }
    
    .nav-link:after {
      background: none repeat scroll 0 0 transparent;
      bottom: 0;
      content: "";
      display: block;
      height: 2px;
      left: 50%;
      position: absolute;
      background: #000;
      transition: width 0.3s ease 0s, left 0.3s ease 0s;
      width: 0;
    }
    
    .nav-link:hover:after,
    .nav-link.active:after {
      width: 100%;
      left: 0;
      background: blue;
    }
    <div class="nav-item">
      <a class="nav-link" href="#">Some Link 1</a>
    </div>
    
    <div class="nav-item">
      <a class="nav-link active" href="#">Some Link 2</a>
    </div>

    我不确定你是否使用 react-router。但如果你是,你可以使用NavLink 来做到这一点,比如

    <NavLink
       className="link-item"
       activeStyle={{ color: 'blue' }}
       to="/"
    >
      Link
    </NavLink>
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 2018-09-11
      • 2021-03-10
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 2013-06-23
      相关资源
      最近更新 更多