实现滑动动画菜单
孙泽辉 Lv5

偶然在网站上看见一带滑动动画的nav,参考资料实现了一个。

效果

鼠标从上一个tag滑到下一个时有highlight移动的动画

image

思路

手动造一个highlight的div,高度写死,宽度因为内容不一样长需要用js计算,获取下一个要展示的tag的宽度

鼠标移入的时候,改highlight的offsetLeft为下一个tag的offsetLeft,顺带切换opacity就做出来了

image

实现

html

1
2
3
4
5
6
7
8
9
<div class="container">
<nav>
<div class="highlight"></div>
<a href="" class="menu-item">home</a>
<a href="" class="menu-item">about</a>
<a href="" class="menu-item">service</a>
<a href="" class="menu-item">contact</a>
</nav>
</div

javscript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const highLight = document.querySelector(".highlight");
const navTags = document.querySelectorAll("nav>a");

const handleMouseEnter = (e) => {
// 计算highlight宽度和位置
const navTag = e.target;
const navWidth = window.getComputedStyle(navTag).getPropertyValue("width");
const pos = navTag.offsetLeft;
// 移入时需要判断上一个元素是否是a-tag
if (e.fromElement.classList.contains("menu-item")) {
highLight.style.width = navWidth;
highLight.style.transition = "all .15s ease-in-out";
highLight.style.transform = `translateX(${pos}px)`;
}else{
// 是从别的地方移入的则不展示移入动画
highLight.style.width = navWidth;
highLight.style.transition = " 0s ease-in-out";
highLight.style.transform = `translateX(${pos}px)`;
}
};

navTags.forEach((item) => {
item.addEventListener("mouseenter", handleMouseEnter);
});

代码放到jsrun里了:

nav滑动tag demo源码预览下载- JSRUN

参考:

JavaScript 滑动背景菜单_哔哩哔哩_bilibili

 Comments
Comment plugin failed to load
Loading comment plugin
Powered by Hexo & Theme Keep
Total words 85.5k