单击带有 id 的链接时,平滑滚动不适用于 Lenis

问题描述 投票:0回答:1

你知道为什么滚动行为:平滑不能与平滑滚动的 Lenis 库一起使用吗?当我评论下面的 Lenis 代码时,它工作得很好。当我添加 Lenis 代码时,当我单击带有 id 的标签时,它不会平滑滚动。

const lenis = new Lenis({
  duration: 2.5
})

function raf(time) {
  lenis.raf(time)
  requestAnimationFrame(raf)
}
requestAnimationFrame(raf)

lenis.on('scroll', ScrollTrigger.update)

gsap.ticker.add((time) => {
  lenis.raf(time * 1000)
})
html {
  scroll-behavior: smooth;
}
 <h2><a class="c-btn" href="#pages-main">scroll down</a></h2>
 
  <section id="pages-main"></section>

你知道为什么滚动行为:平滑不能与平滑滚动的 Lenis 库一起使用吗?当我评论下面的 Lenis 代码时,它工作得很好。当我添加 Lenis 代码时,当我单击带有 id 的标签时,它不会平滑滚动。

const lenis = new Lenis({
  duration: 2.5
})

function raf(time) {
  lenis.raf(time)
  requestAnimationFrame(raf)
}
requestAnimationFrame(raf)

lenis.on('scroll', ScrollTrigger.update)

gsap.ticker.add((time) => {
  lenis.raf(time * 1000)
})
html {
  scroll-behavior: smooth;
}
 <h2><a class="c-btn" href="#pages-main">scroll down</a></h2>
 
  <section id="pages-main"></section>

javascript html css smooth-scrolling
1个回答
0
投票
import { LenisInstance, ScrollToParams, useLenis } from "@studio-freight/react-lenis";

// Using the useLenis hook to get a LenisInstance
  const lenisInstance: LenisInstance = useLenis();

  // Function for smooth scrolling
    const handleClick = (targetElement:string)=>{

    if (targetElement) {
      const scrollToOptions: ScrollToParams = {
        // Customize scroll options if needed
        offset: 0,
        lerp: 0.1,
        duration: 1.5,
        easing: (rawValue: number) => rawValue, // Example easing function
        immediate: false,
        lock: false,
        force: false,
      };

      lenisInstance.scrollTo(targetElement, scrollToOptions);
    }
  }

我为此使用了react-lenis,但它可能也可以与普通的lenis包一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.