vue点击标签滑动到对应模块

mac2024-07-16  47

vue点击标签滑动对应某个模块

文章目录

vue点击标签滑动对应某个模块效果图htmlJsscss

效果图

html

<template> <main class="main"> <!-- 遍历标题 --> <ul class="navMenu"> <li v-for="(item, index) in navList" :key="index" @click="showModule(index)" :class="{actives: active === index}">{{item.title}}</li> </ul> <!-- 遍历模块 --> <div class="contentWrap"> <section :style="`background: ${item.color}` " :class="`commSty module${index}`" v-for="(item, index) in moduleList" :key="index+10"> {{item.content}} </section> </div> </main> </template>

Js

<script> export default { data(){ return{ navList: [ {"title": "推荐"}, {"title": "科技"}, {"title": "时尚"}, {"title": "新闻"}, ], moduleList: [ {"content":"推荐推荐", "color":"red"}, {"content":"科技科技", "color":"yellow"}, {"content":"时尚时尚", "color":"pink"}, {"content":"新闻新闻", "color":"yellowGreen"}, ], active: 0, } }, methods: { showModule(index) { console.log(index); // 给当前点击元素添加类名 this.active = index; //获取元素 var el = document.getElementsByClassName(`module${index}`)[0]; console.log(el.offsetTop); this.$nextTick(function () { // 平滑滑动【这里-55 是当前元素上边界相对body的上偏移量】,可根据需求修改 window.scrollTo({"behavior":"smooth","top":el.offsetTop - 55 }); }) } } } </script>

如需求是通过地址栏参数获取的, 可使用watch监听路由变化

watch: { '$route' (to, from) { // console.log('获取点击的参数---->', this.$route.query.current); let currentModule = this.$route.query.current; // 获取当前操作模块 this.showModule(currentModule); } }, created() { this.getCurrentParams = this.$route.query.current; }, mounted() { if(this.getCurrentParams != undefined) { showModule(this.getCurrentParams); } },

scss

<style lang="scss" scoped> .main { overflow: hidden; .navMenu { display: flex; position: fixed; top: 0; left: 0; height: 55PX; width: 100%; background-image: linear-gradient(90deg, #fe650b 0%, #ff8451 100%); li { display: flex; align-items: center; justify-content: center; flex: 1; color: #fff; } .actives { color: red; } } .contentWrap { margin-top: 55PX; .commSty{ width: 100%; height: 500PX; } } } </style>
最新回复(0)