HTML代码:

<nav>
  <ul>
    <li><a href="#">菜单1</a></li>
    <li><a href="#">菜单2</a></li>
    <li><a href="#">菜单3</a></li>
    <li><a href="#">菜单4</a></li>
    <li><a href="#">菜单5</a></li>
  </ul>
  <div class="indicator"></div>
</nav>

CSS代码:

nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #333;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}
nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
  display: inline-block;
  position: relative;
}
nav li {
  display: inline-block;
  margin: 0 10px;
}
nav a {
  display: inline-block;
  padding: 10px 20px;
  color: #fff;
  text-decoration: none;
}
nav .indicator {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 3px;
  background-color: #fff;
  transition: all 0.3s ease-in-out;
}

JavaScript代码:

$(document).ready(function() {
  var nav = $('nav');
  var indicator = $('.indicator');
  var current_item = null;
  var is_hovered = false;
  
  nav.find('li').mouseenter(function() {
    current_item = $(this);
    is_hovered = true;
    update_indicator();
  });
  
  nav.find('li').mouseleave(function() {
    is_hovered = false;
    update_indicator();
  });
  
  function update_indicator() {
    if (current_item && is_hovered) {
      var left = current_item.position().left;
      var width = current_item.outerWidth();
      indicator.css({
        'left': left + 'px',
        'width': width + 'px'
      });
    } else {
      indicator.css({
        'left': '-100%',
        'width': '0'
      });
    }
  }
  
  $(window).resize(function() {
    update_indicator();
  });
});

解释:

  1. 首先,我们设置了一个固定在页面顶部的导航栏,包含了一些菜单项和一个指示条。

  2. 在JavaScript代码中,我们使用jQuery选择器找到菜单项和指示条,并设置了一些变量。

  3. 当鼠标指针移入到一个菜单项时,我们记录下当前菜单项,并更新指示条的位置和宽度。

  4. 当鼠标指针移出菜单项时,我们将记录的当前菜单项置为空,并隐藏指示条。

  5. 我们还添加了一个窗口大小改变的事件,确保指示条的位置和宽度在窗口大小改变时能够正确地更新

使用javascripthtml5jQuery代码实现网页中导航跟随的效果当鼠标指针移入到导航的某一项时指示条也跟随鼠标指针移动。

原文地址: https://www.cveoy.top/t/topic/fgh6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录