javascript - 在循环中移动元素

标签 javascript html css

我正在尝试将这些框的父项从右移到左,并且我已将动画设置为循环。

@keyframes move {
  to {
    left: -200px;
  }
}
#container {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  animation-name: move;
  animation-duration: 5s;
  animation-iteration-count: infinite;
}
.box {
  display: inline-block;
  width: 200px;
  height: 100px;
  background: red;
  margin: 10px;
}
<div id="container">
  <div class="box"></div>
  <div class="box"></div>
</div>

正如您在动画上方看到的那样,移动 div 并返回到它的位置。我想要的是它继续向左移动,一旦元素离开屏幕我想要它从屏幕右侧返回并转到左侧屏幕 ...

我知道仅靠 CSS 是不可能的。我如何使用 css/JavaScript 实现此目的。

Graphic illustration of what i want to acheive

enter image description here

我希望它一开始穿过屏幕就开始从相反的方向返回屏幕。

最佳答案

如果我没有正确理解您的问题,那么您正在寻找类似于下面的代码片段的内容。如果是这种情况,你不需要 javascript,css 就足够了。

如果你想让它相对于窗口宽度隐藏,你的盒子需要是流动的(百分比而不是固定像素)。您可以使用这些值。

如果你想要固定宽度,你可以创建一个固定宽度的包装器并将其设置为溢出隐藏

/* Fluid */
@keyframes move-1 {
  to {
    left: -50%;
  }
}
@keyframes move-2 {
  to {
    left: -20%;
  }
}
#container {
  width: 100%;
  height: 100px;
  overflow: hidden;
  position: relative;
}
.box {
  position: absolute;
  display: inline-block;
  width: 20%;
  height: 100px;
  background: red;
  animation-duration: 5s;
  animation-iteration-count: infinite;
}
.box:nth-child(1) {
  animation-name: move-1;
  left: 100%;
}
.box:nth-child(2) {
  animation-name: move-2;
  left: 130%;
}



/* Fixed */
@keyframes move-3 {
  to {
    left: -440px;
  }
}
@keyframes move-4 {
  to {
    left: -220px;
  }
}
#container2 {
  width: 200px;
  height: 100px;
  border: 1px solid lightgrey;
  overflow: hidden;
  position: relative;
}

.box2 {
  position: absolute;
  display: inline-block;
  width: 200px;
  height: 100px;
  background: red;
  animation-duration: 5s;
  animation-iteration-count: infinite;
}
.box2:nth-child(1) {
  animation-name: move-3;
  left: 220px;
}
.box2:nth-child(2) {
  animation-name: move-4;
  left: 440px;
}
<h2>Fluid Container</h2>
<div id="container">
  <div class="box"></div>
  <div class="box"></div>
</div>

<h2>Fixed Container</h2>
<div id="container2">
  <div class="box2"></div>
  <div class="box2"></div>
</div>

关于javascript - 在循环中移动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34732113/

相关文章:

javascript - 如何根据 Raphael JS 矩形包含的文本行设置其宽度和高度?

javascript - 将数组从一个函数传递到另一个函数

html - 如果给定绝对位置,Firefox 和 Internet Explorer 不会相对于父级定位

html - 使用百分比时,CSS div 标签不是父级的大小

html - 在移动 View 中将页脚保留在页面底部

javascript - 如何检查是否有任何 JavaScript 事件监听器/处理程序附加到元素/文档?

javascript - react : How should I populate the HTML?

html - 将元素固定到 flex 容器的底部

一旦用户添加了文本,Javascript 按钮就停止写入文本区域

html - 努力将我的 Font Awesome 图标居中