滑动定位+切换定位

<template>
  <div>
    <!-- 固定导航按钮 -->
    <a-affix offset-top="10">
      <a-space>
        <a-button
          v-for="(section, index) in sections"
          :key="section.id"
          :type="activeSection === section.id ? 'primary' : 'default'"
          @click="scrollToSection(section.id)"
        >
          {{ section.name }}
        </a-button>
      </a-space>
    </a-affix>

    <!-- 滚动内容区 -->
    <div ref="scrollContainer" class="content" @scroll="handleScroll">
      <div v-for="(section, index) in sections" :id="section.id" :key="section.id" class="section">
        <h2>{{ section.name }}</h2>
        <p>{{ section.content }}</p>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 定义滚动部分的数据
const sections = ref([
  { id: 'section1', name: 'Section 1', content: 'This is Section 1' },
  { id: 'section2', name: 'Section 2', content: 'This is Section 2' },
  { id: 'section3', name: 'Section 3', content: 'This is Section 3' },
])

// 当前激活的部分
const activeSection = ref('')

// 滚动容器引用
const scrollContainer = (ref < HTMLElement) | (null > null)

// 滚动到指定部分
const scrollToSection = (id) => {
  const element = document.getElementById(id)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

// 滚动监听
const handleScroll = () => {
  console.log('scroll', activeSection.value)
  let currentSection = ''

  // 遍历所有 section,判断它们是否出现在视口中
  sections.value.forEach((section) => {
    const element = document.getElementById(section.id)
    if (element) {
      const rect = element.getBoundingClientRect() //获取元素相对于视口的位置信息,返回一个 DOMRect 对象,包含 top、right、bottom、left、width 和 height 属性。
      // 检查当前 section 是否进入视口中,且距离顶部足够近
      if (
        rect.top >= 0 &&
        rect.top <= (scrollContainer.value?.clientHeight || window.innerHeight) / 2
      ) {
        currentSection = section.id
      }
    }
  })

  // 如果当前激活部分发生变化,则更新 activeSection
  if (currentSection !== activeSection.value) {
    activeSection.value = currentSection
  }
}
</script>
<style scoped>
.content {
  margin-top: 20px;
  height: 500px; /* 设置固定高度 */
  overflow: auto; /* 启用滚动条 */
  border: 1px solid #f0f0f0;
}

.section {
  height: 500px;
  padding: 20px;
  border: 1px solid #f0f0f0;
  margin-bottom: 10px;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值