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

如何基于元素A的view-timeline实现非后代元素B的动画?

问题:非后代元素如何基于其他元素的view-timeline实现动画?

我尝试通过在元素A上设置view-timeline属性,为元素B添加动画。借助view-timeline,只要将其关联到animation-timeline,就能根据元素在视口中的位置触发动画。

MDN文档明确说明:

该名称会在animation-timeline声明中引用,以指明时间线推进时要动画的元素。可以是主体元素本身,也可以是其他元素——当主体元素在滚动区域中移动时,你可以为另一个元素设置动画。

按此理论,只需将元素B的animation-timeline设置为元素A(主体)的view-timeline,就能实现元素B的动画效果(比如缩放、透明度变化):

.container {
    min-height: 200vh;
}

.fixed {
    position: fixed;
    right: 50px;
    top: 50px;
}

.square {
     height: 100px;
     width: 100px;
}

#A {
   background-color: green;
    margin-top: 50%;
    view-timeline: --aTimeline y;
}

#B {
    background-color: red;
    animation-timeline: --aTimeline;
    animation-name: slideInFixedSquare;
    animation-fill-mode: both;
    animation-duration: 1ms; 
}

@keyframes slideInFixedSquare {
    from {
        opacity: 0;
        transform: scaleX(0);
    }

    to {
        opacity: 1;
        transform: scaleX(1);
    }
}
<!-- 不生效 -->
<div class="container">
  <div id="A" class="square"></div>
  <div id="B" class="square fixed"></div>
</div>

<!-- 生效 -->
<div class="container">
  <div id="A" class="square">
     <div id="B" class="square fixed"></div>
  </div>
</div>

但实际测试发现,只有当B是A的后代元素时动画才会生效,而MDN文档并未明确这一限制。请问如何让非后代元素B基于元素A的view-timeline实现动画?


内容的提问来源于stack exchange,提问作者erchenstein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 14:52:14