使用framer-motion的滾動插值justifyContent的技巧
P粉238433862
P粉238433862 2023-08-31 18:42:45
0
1
394
<p>我有一段程式碼可以在x值之間進行動畫,但是當嘗試從justify-content: center轉換到left時無法運作。 </p> <p>以下是程式碼片段:</p> <pre class="brush:php;toolbar:false;">function Navbar() { const { scrollY } = useScroll(); const x = useTransform(scrollY, [0, 100], ["center", "left"]); return ( <motion.div layout className={styles.parent} style={{ justifyContent: x, display: "flex" }} transition={{ duration: 0.5 }} > <Image src="/BlackLogo-2.svg" alt="Cg Logo" width={100} height={100} style={{padding: 20,}} priority /> </motion.div> ) }</pre></p>
P粉238433862
P粉238433862

全部回覆(1)
P粉293341969

我找到了一個解決方案。你只需使用useMotionValueEvent函數來檢查是否滾動超過某一點,並將其設置為狀態,然後必須將你的子元素(我的圖片)包裝在motion.div中,同時在外部div中設置類,如下所示:

function Navbar() {
  const { scrollY } = useScroll();
  const [Scrolled, setScrolled] = useState(false);
  
  useMotionValueEvent(scrollY, "change", (latest) => {
    if (latest > 200) {
      setScrolled(true);
    }
    else {
      setScrolled(false);
    }
  })

  return (
    <div 
      style={{justifyContent: Scrolled? "left" : "center"}}
      className={styles.icon}
    > 
      <motion.div
      layout
      transition={{type: "spring", stiffness: 700, damping: 30}}
      >
        <Image
          src="/BlackLogo-2.svg"
          alt="Cg Logo"
          width={100}
          height={100}
          style={{padding: 20,}}
          priority
        />
      </motion.div>
    </div>
  )

}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!