<header>
  <div id="nav-menu">
    <nav>
      <ul>
        <li class="menu-item"><a href="#">Google</a></li>
        <li class="menu-item"><a href="#">Apple</a></li>
        <li class="menu-item"><a href="#">Windows</a></li>
        <li class="menu-item"><a href="#">Amazon</a></li>
      </ul>
    </nav>
  </div>
</header>
#nav-header {
  position: relative;
}

.line-nav {
  position: absolute;
  height: 2px;
  background-color: #000;
  transition: left 0.3s ease, width 0.3s ease;
}

#nav-menu nav  {
  position: relative;
}

#nav-menu nav  > ul {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
}

#nav-menu nav > ul > .menu-item {
  position: relative;
  padding: 0 20px;
}

#nav-menu nav > ul > .menu-item a {
  text-decoration: none;
  color: #000;
}

/* #nav-menu nav  > ul > .menu-item:hover {
  font-weight: bold;
} */

$(document).ready(function () {
  $("#nav-menu").append(
    '<div class="line-nav" style="left:-80px; width: 96px;"></div>'
  );
  // 監聽 menu-link 的 hover 事件
  $("#nav-menu nav > ul > .menu-item").hover(
    function () {
      var menuPosition = $(this).offset().left; // 取得目標 menu 的左側位置
      var lineWidth = $(this).outerWidth(); // 取得目標 menu 的寬度
      console.log(lineWidth);
      $(".line-nav").css({
        left: menuPosition,
        width: lineWidth
      });
    },
    function () {
      // Hover 結束時將線條恢復到初始位置
      $(".line-nav").css({
        left: "calc(-80px)",
        width: "96px"
      });
    }
  );
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js