在Vue3和TypeScript中实现网站顶部导航栏固定,并在页面滚动大于200px时,顶部导航栏消失,出现新的固定在顶部的导航栏
- 创建一个Vue组件来实现顶部导航栏的逻辑:
<template><div class="navbar-wrapper"><div v-if="showOriginalNav" class="original-navbar">原始的顶部导航栏</div><div v-else class="new-navbar">新的固定在顶部的导航栏</div></div>
</template><script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted } from 'vue';export default defineComponent({name: 'TopNavBar',setup() {const showOriginalNav = ref(true);const handleScroll = () => {if (document.documentElement.scrollTop > 200) {showOriginalNav.value = false;} else {showOriginal.value = true;}}onMounted(() => {window.addEventListener('scroll', handleScroll);});onUnmounted(() => {window.removeEventListener('scroll', handleScroll);});return {showOriginalNav,};},
});
</script><style>
/* 样式 */
</style>
- 在主页面中引入该组件并使用:
<template><template><TopNavBar /><div style="height: 1000px;">内容区域</div></div>
</template><script lang="ts">
import { defineComponent } from 'vue';
import TopNavBar from './TopNavBar.vue';export default defineComponent({name: 'App',components: {TopNavBar,},
});
</script><style lang="scss">
.navbar-wrapper {position: relative;
}.original-navbar {position: fixed;top: 0;left: 0;right: 0;background: white;z-index: 1000;
}.new-navbar {position: fixed;top: 0;left: 0;right: 0;background: white;z-index: 1000;opacity: 0;transition: opacity 0.3s;
}.showNewNavbar {opacity: 1;
}
</style>