You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Intersection Observer实现随滚动方向旋转图片的逻辑调试求助

基于Intersection Observer实现随滚动方向旋转图片的逻辑调试求助

我最近看到一个网站里的滚动动画效果特别棒——当用户滚动页面时,一些图标会跟着旋转。我试着自己复刻这个效果,但总感觉差了点逻辑,尤其是在**准确判断用户的滚动方向(从上到下还是从下到上)**这里卡壳了。

我已经做的尝试:

  • 用Intersection Observer检测图标/图片容器是否进入视口
  • 尝试通过Intersection Observer的boundingClientRect.y来判断滚动方向,以此调整旋转的行为
  • 给Intersection Observer设置了一系列threshold阈值,让回调函数能频繁触发

但还是没摸透完整的逻辑,目前最大的难题就是准确判断用户的滚动方向。

以下是我目前的代码:

function getAngle(str) {
  if (str) {
    let angle = str.split("(");
    let angleArr = angle[1].split("t");
    return parseFloat(angleArr[0]);
  }
}

const globeOptions = {
  rootMargin: '0px',
  threshold: [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
}
let previousY = 0;
let previousRatio = 0;
const globeCallback = entries => {
    entries.forEach(entry => {
        const currentY = entry.boundingClientRect.y
        const currentRatio = entry.intersectionRatio
        const isIntersecting = entry.isIntersecting;
        let prevAngle = entry.target.style.transform ? getAngle(entry.target.style.transform) : 0;
    
        if (currentY < previousY) {
          if (currentRatio > previousRatio && isIntersecting) {
            entry.target.style.transform = `rotate(${prevAngle + 0.2}turn)`;
          } else {
            entry.target.style.transform = `rotate(${prevAngle + 0.2}turn)`;
          }
        } else if (currentY > previousY && isIntersecting) {
          if (currentRatio < previousRatio) {
            entry.target.style.transform = `rotate(${(prevAngle - 0.2) * -1}turn)`;
          } else {
            entry.target.style.transform = `rotate(${(prevAngle - 0.2) * -1}turn)`;
          }
        }
    
        previousY = currentY
        previousRatio = currentRatio
    })
}

const globeobserver = new IntersectionObserver(globeCallback, globeOptions)

const globeTarget = document.querySelector('.globe-box img')
globeobserver.observe(globeTarget)

备注:内容来源于stack exchange,提问作者Pranay kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 18:02:59