比较友好的vue模拟双向锚点的功能

本文介绍了一种利用Vue.js实现网页中平滑滚动效果的方法,并通过监听滚动事件来高亮当前导航项,增强用户体验。具体实现包括定义滚动方法、监听页面滚动以及设置导航项的样式变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、methods里面加上

  jump (index, type) {
      this.nowType = type
      document.querySelector('#' + type).scrollIntoView({
        behavior: 'smooth'
      })
    },
    onScroll () {
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      const _article = document.querySelectorAll('.d_jump')
      _article.forEach((item, index) => {
        if (scrollTop >= item.offsetTop) {
          this.activeStep = index
          console.info(index)
          this.nowType = item.getAttribute('id')
        }
        if (index === 0) {
          if (scrollTop < item.offsetTop) {
            this.nowType = ''
          }
        }
      })
    }

2、mounted里面加上

// 实例创建成功调用一次
    this.onScroll()
    this.$nextTick(function () {
      window.addEventListener('scroll', this.onScroll)
    })

3、html部分

整屏效果块使用 .d_jump类

导航使用jump()方法

<HotNews index="1" class="d_jump" ref="hotNews" id="hotNews"></HotNews>
    <LiveClass index="2" class="d_jump" ref="liveClass" id="liveClass"></LiveClass>
    <WildAnimalLive index="3" class="d_jump" ref="wildAnimalLive" id="wildAnimalLive"></WildAnimalLive>
    <PhotoGallery index="4" class="d_jump" ref="photoGallery" id="photoGallery"></PhotoGallery>
    <DocumentaryFilm index="5" class="d_jump" ref="documentaryFilm" id="documentaryFilm"></DocumentaryFilm>
    <InterestingShortVideo index="6" class="d_jump" ref="interestingShortVideo" id="interestingShortVideo"></InterestingShortVideo>
    <OnlineMuseum v-if="false" index="7" class="d_jump" ref="onlineMuseum" id="onlineMuseum"></OnlineMuseum>
    <ExtinctAnimals index="8" class="d_jump" ref="extinctAnimals" id="extinctAnimals"></ExtinctAnimals>
    <FriendlyLink index="9" class="d_jump" ref="friendlyLink" id="friendlyLink"></FriendlyLink>
 <div class="flex fixed top-32 z-50 right-box flex-col text-center text-white bg-black bg-opacity-40 text-2xl rounded-24px px-10 py-16 font-bold" style="">
      <div class="mb-12 cursor-pointer" @click="jump('1','hotNews')" :style="{ 'color': nowType==='hotNews'? '#FFC400':'white'}">热点资讯</div>
      <div class="mb-12 cursor-pointer" @click="jump('2','liveClass')" :style="{ 'color': nowType==='liveClass'? '#FFC400':'white'}">公共科普直播课堂</div>
      <div class="mb-12 cursor-pointer" @click="jump('3','wildAnimalLive')" :style="{ 'color': nowType==='wildAnimalLive'? '#FFC400':'white'}">野生动物直播信号</div>
      <div class="mb-12 cursor-pointer" @click="jump('4','photoGallery')" :style="{ 'color': nowType==='photoGallery'? '#FFC400':'white'}">高清图片库</div>
      <div class="mb-12 cursor-pointer" @click="jump('5','documentaryFilm')" :style="{ 'color': nowType==='documentaryFilm'? '#FFC400':'white'}">纪录片</div>
      <div class="mb-12 cursor-pointer" @click="jump('6','interestingShortVideo')" :style="{ 'color': nowType==='interestingShortVideo'? '#FFC400':'white'}">趣味短视频</div>
      <div class="mb-12 cursor-pointer" @click="jump('7','onlineMuseum')" :style="{ 'color': nowType==='onlineMuseum'? '#FFC400':'white'}" v-if="false">线上博物馆</div>
      <div class="mb-12 cursor-pointer" @click="jump('8','extinctAnimals')" :style="{ 'color': nowType==='extinctAnimals'? '#FFC400':'white'}">已灭绝动物</div>
      <div class="mb-12 cursor-pointer" @click="jump('9','friendlyLink')" :style="{ 'color': nowType==='friendlyLink'? '#FFC400':'white'}">国内外资源网站</div>
      <div>
        <img src="http://cdn.nature.hanyastar.cn/test/template/round_top.png" class="w-16 mx-auto mb-1.5 cursor-pointer" @click="top()">
        top
      </div>
    </div>

 

### 实现 Vue 项目中的 Y 轴下滑滚动效果 在 Vue 中实现 Y 轴下滑滚动效果通常涉及监听滚动事件并动态加载数据或触发特定行为。以下是基于提供的引用以及常见实践的具体方法。 #### HTML 结构设计 为了支持无限滚动功能,需要定义一个可滚动的容器,并绑定 `@scroll` 事件来检测用户的滚动操作[^2]: ```html <template> <div class="scroll-container" @scroll="handleScroll"> <ul> <li v-for="item in items" :key="item.id">{{ item.text }}</li> </ul> <div v-if="loading" class="loading">加载中...</div> <div v-if="allLoaded" class="end">没有更多内容了</div> </div> </template> ``` 上述结构通过 `v-for` 动态渲染列表项,并提供两个占位符分别用于提示“正在加载”和“已无更多内容”。 --- #### JavaScript 方法逻辑 核心在于计算当前滚动位置是否接近底部,并据此决定是否加载新数据。具体实现如下: ```javascript export default { data() { return { items: [], // 数据列表 loading: false, // 加载状态标志 allLoaded: false // 是否已经加载完毕 }; }, methods: { handleScroll(event) { const container = event.target; if (container.scrollTop + container.clientHeight >= container.scrollHeight - 10 && !this.loading && !this.allLoaded) { // 判断是否接近底部 this.loadMore(); // 如果满足条件,则调用加载函数 } }, loadMore() { this.loading = true; // 设置为加载中 setTimeout(() => { // 模拟异步请求 let newItems = Array.from({ length: 10 }, (_, i) => ({ id: this.items.length + i, text: 'Item ' + (this.items.length + i) })); this.items.push(...newItems); // 添加新的数据 this.loading = false; // 完成后关闭加载状态 if (this.items.length >= 100) { // 假设总共有100条数据 this.allLoaded = true; // 所有数据均已加载完成 } }, 1000); } } }; ``` 此部分代码实现了当用户滚动至接近底部时自动加载更多数据的功能[^1]。 --- #### CSS 样式优化 为了让用户体验更佳,需设置合适的样式以确保滚动区域正常工作: ```css .scroll-container { height: 300px; /* 可视化高度 */ overflow-y: auto; /* 启用垂直滚动 */ border: 1px solid #ccc; /* 边框装饰 */ } .loading, .end { text-align: center; padding: 10px; } ``` 以上样式设置了固定的高度和溢出属性,从而创建了一个可控的滚动环境。 --- #### 双向定位扩展 如果希望进一步增强交互体验(如击左侧菜单跳转到右侧具体内容),则可以引入机制[^3]。例如,在模板中添加 ID 属性并与导航链接关联: ```html <!-- 左侧菜单 --> <ul> <li v-for="(section, index) in sections" :key="index"> <a :href="'#section-' + section.id" @click.prevent="scrollToSection(section.id)"> {{ section.name }} </a> </li> </ul> <!-- 右侧内容 --> <div v-for="(section, index) in sections" :id="'section-' + section.id" :key="index"> <h2>{{ section.title }}</h2> <p>{{ section.content }}</p> </div> ``` 配合以下方法实现平滑滚动: ```javascript methods: { scrollToSection(id) { document.getElementById('section-' + id).scrollIntoView({ behavior: 'smooth', // 平滑过渡 block: 'start' // 对齐顶部 }); } } ``` 该方式不仅能够实现击跳转,还可以结合滚动事件实时更新菜单高亮状态。 --- ### 总结 综上所述,Vue 中的 Y 轴下滑滚动效果可通过监听滚动事件、动态加载数据以及合理配置样式来达成。同时,借助技术还能提升页面互动性和可用性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值