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

如何让其他div相对于已平移的div#foo同步移动?

让多个元素跟随目标div同步移动的解决方案

你当前用transform: translate()移动#foo时,这个属性仅改变元素的视觉位置,不会影响文档流,所以#bar和#bar2会留在原地。要让它们保持相对位置同步移动,有两种可行方案:

方案一:使用共同的内部容器(推荐,动画流畅)

把#foo、#bar、#bar2放在同一个内部容器中,移动这个容器就能让所有元素保持相对位置同步动起来,同时保留transform的流畅动画。

修改后的HTML

<div id="wrapper">
  <div id="inner-container">
    <div id="foo" class="container"></div>
    <div id="bar" class="container"></div>
    <div id="bar2" class="container"></div>
  </div>
</div>
<button id="btn">Move Up</button>

修改后的CSS

#foo {
  background: gray;
}

#bar {
  background: black;
}

#bar2 {
  background: #222222;
}

.up {
  transform: translate(0%, -100%);
}

.container {
  width: 30vw;
  height: 20vh;
}

#inner-container {
  transition: transform 1s linear;
  display: flex;
  flex-direction: column;
}

#wrapper {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

#btn {
  position: absolute;
  top: 20px;
  left: 20px;
}

修改后的JS

document.getElementById('btn').addEventListener('click', function() {
  let innerContainer = document.getElementById('inner-container');
  innerContainer.className += " up";
});

方案二:使用margin代替transform(影响文档流)

如果不想修改HTML结构,可以把transform换成margin-top,因为margin会改变元素在文档流中的位置,从而带动后续元素移动:

修改CSS中的.up类:

.up {
  margin-top: -100%;
  transition: margin-top 1s linear;
}

注意:这种方式会触发浏览器重排,动画流畅度不如transform,且如果容器有其他margin/padding需要额外调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:48:23