我正在尝试制作自己的基本Vanilla JS Carousel。我只是想将每个框架无限地滑动到视图中。
可见加载帧1,所有其他帧均为left:100%
,不可见。
2000毫秒后,第2帧设置为left:0
并滑入视图。同时,将幻灯片1设置为left:-100%
,然后将幻灯片滑出视线。
当第3帧滑入视图时,第2帧设置为left:-100%
,同时第1帧设置为left:100%
,因此它现在再次位于右侧。
所有帧都将继续-应该这样做...
简单地说...它们从队列的后面(右边)开始,移到队列的前面(左边),然后又一个又一个地移到后面。创建连续的幻灯片循环。
对于第一个完整的“队列”,它可以正常工作,但是第二次绕着第3帧和第4帧不返回left:100%
,而是从左侧滑入。他们不会返回队列的后面。
解释此问题的最佳方法是下面的示例。在所有帧正确移动1次后,问题发生在第3帧和第4帧。每个框架都应从右方向向左滑动。
const uspRotator = document.querySelector("#uspRotator")
const uspCount = uspRotator.childElementCount
let actualCount = 2
let i = 2
setInterval(() => {
//Move frame from right to in view
const rightView = document.querySelector("#uspRotator div:nth-child(" + i + ")")
rightView.style.left = 0
rightView.style.zIndex = 2
//Move previous frame to the left
if((actualCount % uspCount) == 1) {
const previousLeft = document.querySelector("#uspRotator div:nth-child(" + uspCount + ")")
previousLeft.style.left = "-100%"
previousLeft.style.zIndex = 0
document.querySelector("#uspRotator div:nth-child(" + (uspCount - 2) + ")").style.left = "100%"
} else {
const previousLeftMinus = document.querySelector("#uspRotator div:nth-child(" + (i - 1) + ")")
previousLeftMinus.style.left = "-100%"
previousLeftMinus.style.zIndex = 0
if(!(i == 2)) {
const previousLeftMinusTwo = document.querySelector("#uspRotator div:nth-child(" + (i - 2) + ")")
previousLeftMinusTwo.style.left = "100%"
previousLeftMinusTwo.style.zIndex = 0
}
}
//move first frame to the left each time
if(actualCount == 2) {
const firstFrame = document.querySelector("#uspRotator div:nth-child(1)")
firstFrame.style.left = "-100%"
firstFrame.style.zIndex = 0
}
i++
actualCount++
//Reset count to start sliding the first USP again
if(i > uspCount) {
i = 1
}
}, 2000)
.rd-usp--container .rd-usp {
width: calc(50% - 80px);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border-width: 0;
height: 52px;
overflow: hidden;
}
.rd-usp--container .rd-usp div {
border-width: 0;
position: absolute;
top: 0;
left: 100%;
width: 100%;
height: 52px;
display: block;
transition: 0.4s;
}
.rd-usp--container .rd-usp div:nth-child(1) {
left: 0;
background: red;
}
.rd-usp--container .rd-usp div:nth-child(2) {
background: blue;
}
.rd-usp--container .rd-usp div:nth-child(3) {
background: yellow;
}
.rd-usp--container .rd-usp div:nth-child(4) {
background: green;
}
.rd-usp--container .rd-usp div:nth-child(5) {
background: purple;
}
.rd-usp--container .rd-usp div:nth-child(6) {
background: grey;
}
.rd-usp--container .rd-usp div:nth-child(7) {
background: orange;
}
<div class="rd-usp--container">
<div class="rd-usp" id="uspRotator">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
</div>