实现导航栏下划线跟随效果

387 阅读1分钟

该demo是导航栏下划线跟随鼠标滑动效果。是基于Vue3写的一个小demo。可以实现下划线滑动跟随效果以及点击选项后隐藏效果。

原理:利用JS控制下划线的位置,先给下划线一个默认的位置信息,当选中某一个菜单选项时,获取该元素的坐标位置和元素宽度,再赋值给下划线。

1.设置菜单栏

// 菜单栏
const tabData = [
  { title: "所有商品", id: 1 },
  { title: "热销", id: 2 },
  { title: "活动与特惠", id: 3 },
  { title: "设计与服务", id: 4 },
  { title: "家居灵感", id: 5 },
  { title: "新品", id: 6 },
  { title: "下载APP", id: 7 },
];

2.渲染

<template>
  <div class="box" ref="NavDom" @mouseleave="handleMouseleave">
    <div
      v-for="(item, index) in tabData"
      :key="item.id"
      class="tab-box"
      @mouseenter="handleMouseenter(index)"
      @click="handleClick(item.id)"
      :class="item.id === ID ? 'active' : ''"
    >
      {{ item.title }}
    </div>
    <i class="nav-style" :style="{ width: flagWidth, left: flagLeft }"></i>
  </div>
</template>

3.核心代码

/**
 *  获取导航栏dom
 */
const NavDom = ref(null);
/**
 * 下划线的宽度
 */
const flagWidth = ref("0px");
/**
 * 下划线位置
 */
const flagLeft = ref("0px");
/**
 * 获取导航栏dom的子节点
 */
const getChildNodes = (index) => {
  const childNode = NavDom.value.childNodes;
  flagWidth.value = childNode[index + 1].clientWidth + "px";
  flagLeft.value = childNode[index + 1].offsetLeft + "px";
};

/**
 * 鼠标移入事件
 */
const handleMouseenter = (index) => {
  getChildNodes(index);
};
/**
 * 鼠标移出事件
 */
const handleMouseleave = () => {
  flagLeft.value = "0px";
  flagWidth.value = "0px";
};
/**
 * 菜单选项点击事件
 */
const ID = ref();
const handleClick = (id) => {
  ID.value = id; //利用ID控制动态类名,使其点击后改变字体颜色
  flagLeft.value = "0px";
  flagWidth.value = "0px";
};

4.相关CSS

.box {
  height: 60px;
  width: 800px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
}
.tab-box {
  box-sizing: border-box;
  height: 100%;
  line-height: 60px;
}
.nav-style {
  position: absolute;
  display: block;
  height: 3px;
  bottom: 0;
  background-color: blue;
  transition: all 0.5s ease-out;
}
.active {
  color: blue;
}