在Vue2和Vue3中,可以使用CSS3来实现导航栏下划线随鼠标滑动而线性滑动至最佳实践的解决方案。以下是一个简单的Vue3示例,展示了如何实现这一效果:
<template>
<nav :style="navStyle" ref="nav">
<ul>
<li v-for="(item, index) in navItems" :key="index">
<a href="#" @mouseenter="setNavUnderline($event, item)" @mouseleave="clearNavUnderline">
{{ item.text }}
</a>
</li>
</ul>
<div class="underline" :style="underlineStyle"></div>
</nav>
</template>
<script>
export default {
data() {
return {
navItems: [
{ text: 'Home', offset: 0 },
{ text: 'About', offset: 0 },
{ text: 'Services', offset: 0 },
{ text: 'Contact', offset: 0 },
],
underlineStyle: {
width: '0',
transform: 'translateX(0)',
},
};
},
methods: {
setNavUnderline(event, item) {
const rect = event.target.getBoundingClientRect();
const navRect = this.$refs.nav.getBoundingClientRect();
const offset = rect.left - navRect.left;
item.offset = offset;
this.underlineStyle = {
width: `${rect.width}px`,
transform: `translateX(${offset}px)`,
};
},
clearNavUnderline() {
this.underlineStyle = {
width: '0',
transform: 'translateX(0)',
};
},
},
computed: {
navStyle() {
return {
position: 'relative',
};
},
},
mounted() {
this.navItems.forEach((item) => {
const el = this.$el.querySelector(`a[href="#${item.text}"]`);
if (el) {
item.offset = el.getBoundingClientRect().left - this.$refs.nav.getBoundingClientRect().left;
}
});
},
};
</script>
<style scoped>
nav {
position: relative;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
li {
display: inline-block;
}
a {
text-decoration: none;
padding: 10px 20px;
}
.underline {
position: absolute;
bottom: 0;
height: 2px;
background-color: #333;
transition: transform 0.3s, width 0.3s;
}
</style>
在这个例子中,我们创建了一个带有下划线的导航栏,下划线通过CSS的transform
属性实现平滑的线性滑动效果。鼠标悬停在导航链接上时,setNavUnderline
方法会计算出下划线应该滑动到的位置,并更新underlineStyle
,导致下划线移动。鼠标离开时,下划线会恢复到原始状态。这个例子使用了Vue3的Composition API,但同样的原理也适用于Vue2。