programing

intersectionObserver/Scrollspy가 있는 요소의 특정 클래스를 표시하려면 어떻게 해야 합니까?

prostudy 2022. 6. 16. 22:03
반응형

intersectionObserver/Scrollspy가 있는 요소의 특정 클래스를 표시하려면 어떻게 해야 합니까?

여기 vue에 있는 내 페이지의 세 섹션이 있습니다.

<section id="home">Home</section>
<section id="about">About</section>
<section id="contact">Contact</section>

Navbar Link를 클릭하면 해당 섹션으로 스크롤됩니다.여기 라우터 링크가 있습니다.

<router-link to="/">Home</router-link>
<router-link to="/#about">About</router-link>
<router-link to="/#contact">Contact</router-link>

기본적으로 이러한 클래스는 활성 페이지 링크에 추가됩니다.

router-link-active router-link-exact-active

<a href="/" class="router-link-active router-link-exact-active" data-v-41458b80="" aria-current="page">Home</a>
<a href="/#about" class="router-link-active router-link-exact-active" data-v-41458b80="" aria-current="page">About</a>
<a href="/#contact" class="router-link-active router-link-exact-active" data-v-41458b80="" aria-current="page">Contact</a>

그러나 모든 섹션이 동일한 인덱스 페이지에 있으므로 이러한 클래스는 모든 탐색바 링크에 추가됩니다.페이지가 특정 섹션에 있을 때 커스텀클래스를 추가하는 방법이 있나요?

이 예시와 같이 교차점 옵서버를 만들려면 다음 코드를 사용할 수 있습니다.

<template>
  <div>
    <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">
      Intersection observer example
    </a>

    <p
      v-observe-visibility="{
        callback: resetHashUrl,
        intersection: {
          threshold: 0.5,
        },
      }"
      style="background-color: hsl(0, 0%, 80%); height: 100vh"
    >
      top block (triggered at 50% of the block)
    </p>

    <p
      v-observe-visibility="{
        callback: (isVisible, entry) => pushNewHash(isVisible, entry, 'center'),
        intersection: {
          threshold: 0.7,
        },
      }"
      style="background-color: hsl(210, 17%, 40%); color: hsl(0, 0%, 100%); height: 100vh"
    >
      center block (triggered if at least 70% of the block visible aka threshold value)
    </p>

    <p
      v-observe-visibility="{
        callback: (isVisible, entry) => pushNewHash(isVisible, entry, 'end'),
        intersection: {
          threshold: 0.3,
        },
      }"
      style="background-color: hsl(210, 50%, 13%); color: hsl(0, 0%, 100%); height: 100vh"
    >
      end block (triggered if at least 30% of the block visible aka threshold value)
    </p>
  </div>
</template>

<script>
import Vue from 'vue'
import { ObserveVisibility } from 'vue-observe-visibility'

Vue.directive('observe-visibility', ObserveVisibility)

export default {
  methods: {
    resetHashUrl(isVisible, _entry) {
      if (isVisible) history?.replaceState(null, null, ' ')
    },
    pushNewHash(isVisible, _entry, newHash) {
      if (isVisible) location.hash = newHash
    },
  },
}
</script>

vue-observe-visibility에 의존하며 많은 구성이 필요하지 않고 매우 잘 작동합니다.


다음과 같이 간단한 스크롤 스크롤을 원하시면 https://github.com/ibufu/vue2-scrollspy 패키지를 이용하실 수 있습니다.


좀 더 적합한 예를 사용하여 편집하십시오.현재 경로에 따라 일부 클래스를 적용하거나 매개 변수를 전달하는 경우 이 코드 조각입니다.

<template>
  <div>
    <button :class="{ 'custom-class': isOnSpecificPath('/test') }">Click me</button>
    <button :class="{ 'custom-class': isOnSpecificPath('/index') }">Click me</button>
  </div>
</template>

<script>
export default {
  methods: {
    isOnSpecificPath(pathToTest) {
      return this.$route.path === pathToTest
    },
  },
}
</script>

<style>
.custom-class {
  color: hsl(39, 100%, 46%);
  font-weight: 700;
}
</style>

여기에 이미지 설명 입력

언급URL : https://stackoverflow.com/questions/68264650/how-to-display-specific-classes-on-an-element-with-an-intersectionobserver-scrol

반응형