gpt4 book ai didi

javascript - 在循环中移动元素

转载 作者:太空宇宙 更新时间:2023-11-03 23:06:05 25 4
gpt4 key购买 nike

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

@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com