【问题标题】:How to detect when the user has scrolled to a certain area on the page using JavaScript? and then run an animation?如何检测用户何时使用 JavaScript 滚动到页面上的某个区域?然后运行动画?
【发布时间】:2022-02-10 20:30:11
【问题描述】:

如何使用 JavaScript 检测用户何时滚动到页面上的某个区域?然后运行动画? 我需要在滚动到该部分时运行动画,如果您知道问题的任何部分,请提供帮助。

【问题讨论】:

    标签: javascript animation css-animations


    【解决方案1】:

    你可能想看看提供这种功能的 Intersection Observer API。

    来自 Intersection Observer MDN 文档 -

    Intersection Observer API 提供了一种异步观察的方法 目标元素与祖先的交集的变化 元素或顶级文档的视口。

    有关更多信息,请查看 mdn 的关于交叉点观察者 API 的页面 - https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

    【讨论】:

    • 使用这个 API 是滚动时运行动画的最佳方法吗?
    【解决方案2】:

    您正在寻找IntersectionObserver:

    const observer = new IntersectionObserver((nodes)=>{
        nodes.forEach(node =>
          node.target.classList.toggle('visible', node.isIntersecting)
        )
    });
    
    observer.observe(document.querySelector('.node'))
    .node {
      width: 40px;
      height: 40px;
      background: red;
      margin: 500px;
      transition: 1s;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .node.visible {
      background: lightgreen;
      border-radius: 50%;
      color: white;
    }
    <div class='node'>x</div>

    【讨论】:

    • 滚动时是否使用此 API 运行动画的最佳方法?
    • 是的,这绝对是最好的方法
    【解决方案3】:

    如果它不必在 Vanilla Javascript 中,你可以查看这个库 https://greensock.com/scrolltrigger/

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多