无限轮播 - 使用setInterval

时间:2017-12-10 11:20:47

标签: javascript css carousel

请您查看此代码:

当我想删除move

时,我遇到了问题



let lis = document.querySelectorAll('li')
let arr =  [];

for (let i = 0; i < lis.length; i++) {
	arr.push(lis[i]);
}

setInterval( function () {
		let splice = arr.splice(0,1);
    splice[0].classList.add('move');
    arr.push(splice[0]);
},3500)
&#13;
.red {
  background-color: red;
}
.green {
  background-color: green;
}
.yellow {
  background-color: yellow;
}
.blue {
  background-color: blue;
}

.slideshow {
   width: 350px;
   height: 200px;
   overflow: hidden;
   border: 3px solid #F2F2F2;
}

.slideshow ul {
    /* 4 images donc 4 x 100% */
   width: 400%;
   height: 200px;
   padding:0; margin:0;
   list-style: none;
   transition: 2s;
}
.slideshow li {
   float: left;
   width: 25%;
   height: 200px;
   transition: .5s;
}
.move {
  margin-left: -25%;
  transition: .5s;
}
&#13;
<div class="slideshow">
	<ul>
		<li class='red'></li>
		<li class='green'></li>
		<li class='yellow'></li>
		<li class='blue'></li>
	</ul>
</div>
&#13;
&#13;
&#13;

非常感谢

修改

https://jsfiddle.net/o00nu4w8/

使用console.log,我可以得到我想要的效果,但是会出现任何动画

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情。使用您在每个步骤中递增的索引,当您到达最后一个时,删除所有move类,然后重新开始。

&#13;
&#13;
let lis = document.querySelectorAll('li')
let c = 0;


setInterval(function() {
  if (c == lis.length -1) {
    c = 0;
    for (let i = 0; i < lis.length; i++)
      lis[i].classList.remove('move');
  } else {
    lis[c].classList.add('move');
    c++;
  }
}, 3500)
&#13;
.red {
  background-color: red;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}

.blue {
  background-color: blue;
}

.slideshow {
  width: 350px;
  height: 200px;
  overflow: hidden;
  border: 3px solid #F2F2F2;
}

.slideshow ul {
  /* 4 images donc 4 x 100% */
  width: 400%;
  height: 200px;
  padding: 0;
  margin: 0;
  list-style: none;
  transition: 2s;
}

.slideshow li {
  float: left;
  width: 25%;
  height: 200px;
  transition: .5s;
}

.move {
  margin-left: -25%;
  transition: .5s;
}
&#13;
<div class="slideshow">
  <ul>
    <li class='red'></li>
    <li class='green'></li>
    <li class='yellow'></li>
    <li class='blue'></li>
  </ul>
</div>
&#13;
&#13;
&#13;