头部导航栏获取scrollTop失败

本文探讨了在特定页面上使用JS获取scrollTop遇到的问题,并发现是由于body设置了height:100%导致无法正确获取。通过调整样式表设置解决了此问题。

自己的导航栏需要获取scrollTop来改变样式,用js写的通用文件。其他页面都可以正常获取,唯独一个页面不行。在论坛找了很久,有说获取scrollTop方式不对的要用

var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;

这是通用方法。

但是我的问题不是这个,是由于该页面的样式表的body设置了height:100% ,这个设置就会导致获取不到,把他删除就行了。

<template> <div class="container"> <!-- 左侧Tab导航 --> <div class="tabs"> <div v-if="sections.length > 0" class="tabs-wrapper"> <div v-for="(section, index) in sections" :key="index" :class="[&#39;tab&#39;, { active: activeIndex === index }]" @click="scrollToSection(index)"> <div>{{ section.name }}</div> </div> </div> <div v-else class="empty-container"> <a-empty description="暂无分类" /> </div> </div> <!-- 右侧内容区域 --> <div class="content"> <!-- 粘性定位的表单 --> <a-form :model="searchForm" label-align="left" auto-label-width layout="inline" :size="&#39;large&#39;" class="search-header"> <a-form-item style="width: 320px;" field="base_title" label="能力名称:" size="large"> <a-input allow-clear v-model="searchForm.base_title" placeholder="搜索能力..." @press-enter="fetchTableData" @clear="resetSearch"> <template #prefix> <icon-search /> </template> </a-input> </a-form-item> <a-form-item> <a-space size=&#39;large&#39;> <a-button type="primary" size="medium" @click="fetchTableData"> <template #icon><icon-search /></template>查询 </a-button> <a-button type="outline" size="medium" @click="resetSearch"> <template #icon><icon-refresh /></template>重置 </a-button> </a-space> </a-form-item> </a-form> <!-- 加载状态 --> <a-spin :loading="loading" style="width: 100%"> <!-- 使用锚点的章节 --> <div v-if="sections.length > 0" class="section-container" ref="contentRef" @scroll="onScroll"> <div v-for="(section, index) in sections" :key="index" :id="section.id" :ref="el => sectionRefs[index] = el" class="section"> <!-- 一级分类标题 --> <div class="section-title"> <icon-apps /> {{ section.name }} </div> <!-- 二级分类循环 --> <template v-for="(subSection, subIndex) in section.children" :key="subIndex"> <!-- 二级分类标题 --> <div class="title">{{ subSection.name }}</div> <!-- 三级分类内容 --> <div class="sub-content"> <div v-for="(item, itemIndex) in subSection.children" :key="itemIndex" class="content-item" @click="sceneDetail(item)"> <!-- 背景图片层 --> <div class="img-wrapper"> <img :src="item.image" alt="能力背景" /> </div> <!-- 内容卡片 --> <div class="item"> <div class="item-image"> <img v-if="item.image" :src="item.image" alt="能力图标" /> <div v-else class="image-placeholder"> <a-image width="100" height="100" src="some-error.png" /> </div> </div> <div class="item-text"> <div class="item-title">{{ item.title }}</div> <div class="item-desc">{{ item.description }}</div> </div> </div> </div> </div> </template> </div> </div> <div v-else class="empty-container"> <a-empty description="暂无能力数据" /> </div> </a-spin> </div> </div> </template> <script setup lang="ts"> import { ref, onMounted, nextTick, reactive } from &#39;vue&#39;; import { IconSearch, IconApps, IconRefresh } from &#39;@arco-design/web-vue/es/icon&#39;; import { Message } from &#39;@arco-design/web-vue&#39;; import { IconImage } from &#39;@arco-design/web-vue/es/icon&#39;; import { useAbilityMallStore } from &#39;@/store/modules/ability-mall&#39;; import { storeToRefs } from &#39;pinia&#39;; import { useRouter } from &#39;vue-router&#39;; import { getAbilityMallList, getabilityMallDetails, createAbilityMall, } from &#39;@/api/abilityMall&#39;; const abilityMallStore = useAbilityMallStore(); const { abilityMallList, abilityMallDetails } = storeToRefs(abilityMallStore); const { getabilityMallDetailsStore } = abilityMallStore; const router = useRouter(); // 定义三级分类数据结构 interface CategoryItem { id: string; title: string; description: string; image: string; } interface SubCategory { id: string; name: string; children: CategoryItem[]; } interface MainCategory { id: string; name: string; children: SubCategory[]; } // 状态管理 // 存储各个section的DOM引用 const sectionRefs = ref([]); // 右侧滚动区域的引用 const contentRef = ref(null); // 记录当前选中的Tab索引 const activeIndex = ref(0); const loading = ref(false); const sections = ref([]); const searchForm = reactive({ base_title: &#39;&#39;, }); // 更高效的数据转换函数 const transformData = (apiData: any[]): MainCategory[] => { const categoryMap = new Map<string, MainCategory>(); const subcategoryMap = new Map<string, SubCategory>(); apiData.forEach((item) => { const categoryName = item.base_category; const categoryId = categoryName.replace(/\s+/g, &#39;-&#39;).toLowerCase(); // 处理一级分类 if (!categoryMap.has(categoryId)) { categoryMap.set(categoryId, { id: categoryId, name: categoryName, children: [], }); } const category = categoryMap.get(categoryId)!; // 处理二级分类 const subcategoryName = item.base_subcategory; const subcategoryId = `${categoryId}-${subcategoryName .replace(/\s+/g, &#39;-&#39;) .toLowerCase()}`; if (!subcategoryMap.has(subcategoryId)) { const subcategory: SubCategory = { id: subcategoryId, name: subcategoryName, children: [], }; subcategoryMap.set(subcategoryId, subcategory); category.children.push(subcategory); } const subcategory = subcategoryMap.get(subcategoryId)!; // 添加三级分类项 subcategory.children.push({ id: item.id, title: item.base_title, description: item.base_content, image: item.base_image, // 添加图片字段 }); }); return Array.from(categoryMap.values()); }; // 滚动到指定章节 - 修复滚动位置计算 // 滚动到指定章节 - 修复滚动位置计算 const scrollToSection = (index) => { if (sectionRefs.value[index]) { // 直接使用section在容器中的偏移位置 const targetOffset = sectionRefs.value[index].offsetTop; contentRef.value.scrollTo({ top: targetOffset, behavior: &#39;smooth&#39; }); } }; // 处理滚动事件 - 修复滚动位置判断逻辑 // 处理滚动事件 - 修复滚动位置判断逻辑 const onScroll = () => { const scrollTop = contentRef.value.scrollTop; const containerHeight = contentRef.value.clientHeight; // 修复最后两个section无法选中的关键逻辑 let currentActive = activeIndex.value; // 检查是否滚动到底部 const isAtBottom = scrollTop + containerHeight >= contentRef.value.scrollHeight - 5; if (isAtBottom && sectionRefs.value.length > 0) { // 滚动到底部时激活最后一个section currentActive = sectionRefs.value.length - 1; } else { // 遍历所有section找到当前激活的 for (let i = 0; i < sectionRefs.value.length; i++) { const section = sectionRefs.value[i]; const sectionTop = section.offsetTop; const sectionBottom = sectionTop + section.offsetHeight; // 当前section是否在视口内 if (scrollTop < sectionBottom && (i === sectionRefs.value.length - 1 || scrollTop < sectionRefs.value[i + 1].offsetTop)) { currentActive = i; break; } } } activeIndex.value = currentActive; }; // 重置搜索 const resetSearch = () => { searchForm.base_title = &#39;&#39;; fetchTableData(); }; // 获取数据 async function fetchTableData() { loading.value = true; try { const { data } = await getAbilityMallList(searchForm); const fakeData = data.filter((item) => item.deleted === 0); // const fakeData = Array.from({ length: 100 }, (_, index) => ({ // id: `item-${index}`, // base_category: `一级分类 ${Math.floor(Math.random() * 20)}`, // base_subcategory: `二级分类 ${Math.floor(Math.random() * 10)}`, // base_title: `能力名称 ${index + 1}`, // base_content: `描述内容 ${index + 1}`, // base_image: `https://via.placeholder.com/100?text=Image${index + 1}`, // deleted: Math.random() > 0.2 ? 0 : 1, // 80% chance of being valid // })); // 使用模拟数据 sections.value = transformData(fakeData || []); // 重置引用 nextTick(() => { sectionRefs.value = []; // 初始化滚动监听 setTimeout(() => { if (sections.value.length > 0) { scrollToSection(0); } }, 100); }); } catch (error) { console.error(&#39;获取能力模型失败:&#39;, error); Message.error(&#39;获取能力模型失败&#39;); } finally { loading.value = false; } } // 跳转详情 const sceneDetail = async (item: CategoryItem) => { loading.value = true; await getabilityMallDetailsStore(item.id); // router.push(`/ability/details/`); router.push({ path: &#39;/ability/details/&#39;, query: { id: item.id }, }); loading.value = false; }; // 生命周期钩子 onMounted(() => { fetchTableData(); }); </script> <style scoped> .container { display: flex; height: 100vh; position: relative; padding: 0; background: #fff; font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, Roboto, Oxygen, Ubuntu, Cantarell, &#39;Open Sans&#39;, &#39;Helvetica Neue&#39;, sans-serif; } /* 左侧导航栏样式 */ .tabs { width: 200px; padding: 20px 0; flex-shrink: 0; position: sticky; top: 0; max-height: 100vh; overflow-y: auto; z-index: 10; background: #f9fafb; border-right: 1px solid #e5e6eb; .tabs-wrapper { padding: 0 10px; } .tab { height: 44px; line-height: 44px; text-align: center; margin: 8px 0; font-size: 15px; color: #1d2129; cursor: pointer; position: relative; transition: all 0.3s ease; border-radius: 6px; overflow: hidden; font-weight: 500; &:hover { background: #f2f3f5; color: #3261CE; transform: translateX(3px); } } .tab.active { color: #3261CE; background: #e8f3ff; font-weight: 600; box-shadow: 0 1px 4px rgba(22, 93, 255, 0.15); &::before { content: &#39;&#39;; position: absolute; left: 0; top: 0; height: 100%; width: 3px; background: #3261CE; } } .empty-container { padding: 40px 20px; } } /* 右侧内容区域 */ .content { flex: 1; height: 100%; position: relative; padding: 0; overflow: hidden; display: flex; flex-direction: column; } /* 搜索头部样式 */ .search-header { width: 100%; display: flex; gap: 16px; padding: 15px 24px; background: #fff; border-bottom: 1px solid #e5e6eb; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03); position: sticky; top: 0; z-index: 20; .header-title { font-size: 20px; font-weight: 600; margin-right: 20px; color: #1d2129; } } /* 分类区域样式 - 关键修改 */ .section-container { flex: 1; overflow-y: auto; scroll-behavior: smooth; padding: 0 24px; position: relative; height: calc(100vh - 80px); /* 减去搜索栏高度 */ } .section { padding: 32px 0; border-bottom: 1px solid #e5e6eb; &:first-child { padding-top: 24px; } &:last-child { border-bottom: none; } } .section-title { font-size: 22px; color: #1d2129; padding-bottom: 16px; margin-bottom: 16px; border-bottom: 1px solid #e5e6eb; font-weight: 600; display: flex; align-items: center; .arco-icon { margin-right: 10px; color: #3261CE; font-size: 20px; } } .title { font-size: 18px; color: #3261CE; margin: 24px 0 16px; padding-left: 12px; border-left: 4px solid #3261CE; font-weight: 500; } /* 内容项网格布局 */ .sub-content { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 20px; margin-top: 8px; } /* 内容项样式 */ .content-item { position: relative; height: 95px; cursor: pointer; border-radius: 8px; overflow: hidden; box-shadow: 0 3px 6px rgba(0, 0, 0, 0.03); transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); background: #fff; border: 1px solid #e5e6eb; /* 背景图片容器 */ .img-wrapper { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; opacity: 0; transform: scale(1.05); transition: all 0.5s cubic-bezier(0.22, 0.61, 0.36, 1); img { width: 100%; height: 100%; object-fit: cover; filter: blur(0); transition: filter 0.5s ease; } } /* 悬停效果 */ &:hover { transform: translateY(-5px); box-shadow: 0 12px 25px rgba(22, 93, 255, 0.2); border-color: rgba(22, 93, 255, 0.3); .img-wrapper { opacity: 1; transform: scale(1); img { filter: blur(4px) brightness(0.9); } } .item { background: rgba(255, 255, 255, 0.85); backdrop-filter: blur(4px); } .item-image img { transform: scale(1.8); } } } /* 内容卡片样式 */ .item { display: flex; position: relative; overflow: hidden; border-radius: 8px; width: 100%; height: 100%; z-index: 2; background: rgba(255, 255, 255, 0.95); transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); } /* 图片样式 */ .item-image { width: 100px; height: 100%; flex-shrink: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; background: #f7f8fa; transition: background 0.3s ease; img { width: 60px; height: 60px; object-fit: contain; display: block; transition: transform 0.5s cubic-bezier(0.22, 0.61, 0.36, 1); } .image-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; color: #c9cdd4; .arco-icon { font-size: 32px; } } } /* 文本区域样式 */ .item-text { flex: 1; padding: 16px 12px; display: flex; flex-direction: column; justify-content: center; overflow: hidden; } .item-title { font-size: 16px; color: #1d2129; font-weight: 500; margin-bottom: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: color 0.3s ease; } .item-desc { font-size: 13px; color: #86909c; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; line-height: 1.5; transition: color 0.3s ease; } /* 响应式调整 */ @media (max-width: 992px) { .container { flex-direction: column; } .tabs { width: 100%; position: sticky; top: 0; z-index: 30; display: flex; overflow-x: auto; padding: 10px 0; height: auto; border-right: none; border-bottom: 1px solid #e5e6eb; .tabs-wrapper { display: flex; padding: 0 16px; } .tab { flex-shrink: 0; margin: 0 8px; padding: 0 16px; height: 36px; line-height: 36px; } } .content { margin-left: 0; } .search-header { padding: 12px 16px; flex-wrap: wrap; } .section-container { padding: 0 16px; height: calc(100vh - 140px); /* 调整移动端高度 */ } .section { padding: 24px 0; } } @media (max-width: 576px) { .sub-content { grid-template-columns: 1fr; } .header-title { display: none; } .search-header { :deep(.arco-form-item) { width: 100%; margin-bottom: 12px; } } .section-container { height: calc(100vh - 180px); /* 调整小屏幕高度 */ } .content-item { height: 110px; } .item-image { width: 80px; } } </style> 选不中最后两个
最新发布
07-29
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值