滑动菜单组件封装
孙泽辉 Lv5

今天将周末写的滑动菜单添加到客户网站上,实际使用上和demo有些差距

因为客户的网站是会有二级菜单的,原本nav>a的写法要重新换成ul>li,这个不是很麻烦

image

差不多是这样,a再包一层li,li单独是highlight

为了方便调用这一坨代码,我把他用类包起来了,(貌似类就是为了打包用的)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 起了个很高大上的名字,实际很low
class awesomeNav {
constructor({
highLight, navTag
}) {
this.highLight = document.querySelector(highLight);
this.navTags = document.querySelectorAll(navTag);
console.log(this.highLight)
// 这边直接绑定,this会指向事件对象,所以包一层箭头函数
this.navTags.forEach((item) => {
item.addEventListener("mouseenter", (e) => this.handleMouseEnter(e));
});
}
handleMouseEnter(e) {
// 计算highlight宽度和位置
const navTag = e.target;
const navWidth = window.getComputedStyle(navTag).getPropertyValue("width");
const pos = navTag.offsetLeft;

if (e.fromElement.classList.contains("menu-item")) {
this.highLight.style.width = navWidth;
this.highLight.style.transition = "all .15s ease-in-out";
this.highLight.style.transform = `translateX(${pos}px)`;
} else {
this.highLight.style.width = navWidth;
this.highLight.style.transition = " 0s ease-in-out";
this.highLight.style.transform = `translateX(${pos}px)`;
}
};
}
// 传入selector就可以跑了
new awesomeNav({
highLight: ".nav .highlight",
navTag: "ul.nav>li"
});

经过一番样式调整,跑起来的效果是这样的:

image

这不是图片掉帧!动画都没了,和手动改背景色一样了,遂排查问题

发现是li之间有间隙,我a宽度都是padding顶的,不可能有间隙,li也没用多余margin。

谷歌一下,是因为给li设置了inline-block 所以li之间的换行被渲染成空格了

image

解决方法:

1
2
3
4
5
6
ul.nav {
letter-spacing: -5px;
}
ul.nav li {
letter-spacing: normal;
}
image

然后就解决了

image

这个问题我们之前上课老师写小卡片就用的ul>li,上课翻车了,图片旁边总有间隙,当时是删掉换行解决的。所以我能立即想出来是间隙的问题

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