VueJS3中滚动时用搜索div替换fixed-top导航栏的实现方法
实现谷歌搜索式滚动导航替换效果
要实现你要的效果,需要跟踪滚动位置、滚动方向,以及页面中searchdiv的位置,然后基于这些条件切换导航栏和搜索组件的显示状态,具体步骤如下:
1. 添加响应式状态变量
在组件的data中新增用于跟踪关键状态的变量:
data() { return { navbarVisible: true, // 原导航栏初始显示 searchComponentVisible: false, // 搜索组件初始隐藏 lastScrollY: 0, // 记录上一次滚动的位置 searchDivTop: 0 // 记录searchdiv距离页面顶部的距离 } }
2. 获取searchdiv的位置
在mounted钩子中获取searchdiv的顶部偏移量,确保DOM渲染完成后再获取元素:
mounted() { console.log("HomeLandingComponent mounted"); // 这里假设你的searchdiv设置了ref="searchDiv",也可以用document.querySelector选择器 const searchDiv = this.$refs.searchDiv; if (searchDiv) { this.searchDivTop = searchDiv.offsetTop; } }
记得给页面中的searchdiv添加ref属性:
<div ref="searchDiv" class="searchdiv">你的搜索区域内容</div>
3. 重写滚动处理方法
替换原有的handleScroll,根据滚动方向和位置判断显示哪个组件:
handleScroll() { const currentScrollY = window.scrollY; const isScrollingDown = currentScrollY > this.lastScrollY; if (isScrollingDown) { // 向下滚动逻辑 if (currentScrollY >= this.searchDivTop) { // 滚动到searchdiv顶部时,显示搜索组件,隐藏原导航栏 this.searchComponentVisible = true; this.navbarVisible = false; } else { // 未到达searchdiv位置时,隐藏导航栏 this.navbarVisible = false; this.searchComponentVisible = false; } } else { // 向上滚动逻辑 if (currentScrollY <= 0) { // 回到页面顶部时,显示原导航栏,隐藏搜索组件 this.navbarVisible = true; this.searchComponentVisible = false; } else { // 向上滚动但未到顶部,保持显示搜索组件 this.searchComponentVisible = true; this.navbarVisible = false; } } // 更新上一次滚动位置 this.lastScrollY = currentScrollY; }
4. 模板中添加条件渲染
在组件模板里根据状态变量控制导航栏和搜索组件的显示:
<!-- 原fixed-top导航栏 --> <nav v-if="navbarVisible" class="fixed-top">原导航栏内容</nav> <!-- 搜索组件,需设置fixed-top样式 --> <SearchComponent v-if="searchComponentVisible" class="fixed-top" /> <!-- 页面中的searchdiv --> <div ref="searchDiv" class="searchdiv">页面内的搜索区域</div>
完整组件代码示例
export default { data() { return { navbarVisible: true, searchComponentVisible: false, lastScrollY: 0, searchDivTop: 0 }; }, created() { window.addEventListener('scroll', this.handleScroll); }, destroyed() { window.removeEventListener('scroll', this.handleScroll); }, mounted() { console.log("HomeLandingComponent mounted"); const searchDiv = this.$refs.searchDiv; if (searchDiv) { this.searchDivTop = searchDiv.offsetTop; } }, methods: { handleScroll() { const currentScrollY = window.scrollY; const isScrollingDown = currentScrollY > this.lastScrollY; if (isScrollingDown) { if (currentScrollY >= this.searchDivTop) { this.searchComponentVisible = true; this.navbarVisible = false; } else { this.navbarVisible = false; this.searchComponentVisible = false; } } else { if (currentScrollY <= 0) { this.navbarVisible = true; this.searchComponentVisible = false; } else { this.searchComponentVisible = true; this.navbarVisible = false; } } this.lastScrollY = currentScrollY; } } };
注意事项
- 确保搜索组件的
fixed-top样式和原导航栏一致,避免切换时出现布局跳动 - 如果页面有动态内容导致
searchdiv位置变化,需要在内容更新后重新计算searchDivTop(比如用watch监听相关数据,或调用方法重新获取)
内容的提问来源于stack exchange,提问作者wenreloz
相关产品推荐
相关产品推荐

