欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 八卦 > 用原生css制作一个侧边导航组件

用原生css制作一个侧边导航组件

2025/2/7 3:16:53 来源:https://blog.csdn.net/m0_45159572/article/details/144395647  浏览:    关键词:用原生css制作一个侧边导航组件

因为用于vue项目所以是一个.vue的组件,组件这样写后调用只需传参整体页面id和板块标题

引用代码 

组件代码

<template><div class="left-nav"><div v-for="(item, index) in items" :key="index" @click="scrollToSection(item)":class="{ active: item === activeItem }" class="nav-item">{{ item }}</div><div class="nav-back" @click="backTop">回到顶部<img src="../../assets/images/productCenter/backTop.png" alt=""/></div></div>
</template><script>export default {name: 'LeftNav',props: {items: {type: Array,required: true},//传参来的标题名称topId: String//运用整体页面的id},data() {return {activeItem: '',//触发的itemobservers: []//观察数组}},mounted() {this.activeItem = this.items[0];this.setupObservers();},beforeDestroy() {this.observers.forEach(observer => observer.disconnect());},methods: {/*** 监听滚动* @param item*/scrollToSection(item) {this.activeItem = item;const element = document.querySelector(`#${item}`);if (element) {element.scrollIntoView({ behavior: 'smooth' });}},/*** 回到顶部*/backTop() {const element = document.querySelector(`#${this.topId}`);if (element) {element.scrollIntoView({ top: 0, behavior: 'smooth' });}},/*** 设置观察者*/setupObservers() {this.items.forEach(item => {const element = document.querySelector(`#${item}`);if (!element) return;const observer = new IntersectionObserver(entries => {entries.forEach(entry => {if (entry.isIntersecting) {this.activeItem = entry.target.id;}});}, { threshold: 0.5 }); // 设置阈值为0.5,即元素50%可见时触发observer.observe(element);this.observers.push(observer);});}}
}
</script><style scoped>.left-nav {position: fixed;top: 130px;left: 80px;width: 114px;padding: 20px 0;z-index: 999;box-sizing: border-box;background: rgba(255, 255, 255, 1);box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.05);border-radius: 4px 4px 4px 4px;border: 1px solid #DCDCDC;
}.nav-item {padding: 10px;font-size: 14px;cursor: pointer;text-align: center;transition: color 0.3s, border-left 0.3s;
}.nav-item:hover {color: #CF9027;
}.nav-item.active {font-weight: bold;font-size: 14px;color: #CF9027;border-left: 3px solid #CF9027;
}.nav-back {display: flex;justify-content: center;align-items: center;padding: 10px 0 0 13px;color: #CF9027;cursor: pointer;
}.nav-back img {position: relative;left: 6px;width: 16px;height: 16px;
}
</style>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com