console
<style>
* {
margin: 0;
padding: 0;
}
ul,
ol {
list-style: none;
}
.carousel-container {
overflow: hidden;
margin: auto;
width: 300px;
height: 120px;
}
.carousel-container ul {
width: 100%;
height: 100%;
white-space: nowrap;
font-size: 0;
}
.carousel-container ul li {
font-size: 12px;
display: inline-block;
width: 100%;
height: 100%;
}
.image1 {
background: red;
}
.image2 {
background: green;
}
.image3 {
background: blue;
}
</style>
<div class="carousel-container">
<ul class="carousel">
<li class="image1"></li>
<li class="image2"></li>
<li class="image3"></li>
</ul>
</div>
<button onclick=test.prev()>prev</button>
<button onclick=test.next()>next</button>
<script>
const run = (container) => {
const containerWidth = container.offsetWidth
const containerRealWidth = containerWidth * container.children.length
const defaultLeft = containerWidth*-1
const prefix = container.lastElementChild.cloneNode(true)
const suffix = container.firstElementChild.cloneNode(true)
container.append(suffix)
container.insertBefore(prefix,container.firstElementChild)
let curLeft = defaultLeft
container.style.marginLeft = `${curLeft}px`
let isOnUpdate = false
const update = () => {
isOnUpdate = true
container.style.transition = `margin-left .5s`
container.style.marginLeft = `${curLeft}px`
setTimeout(()=>{
isOnUpdate =false
if(-1*curLeft >= containerRealWidth+containerWidth){
curLeft = defaultLeft
container.style.transition = `unset`
container.style.marginLeft = `${curLeft}px`
}else if(curLeft >= 0){
curLeft = -1*containerRealWidth
container.style.transition = `unset`
container.style.marginLeft = `${curLeft}px`
}
console.log(curLeft)
},500)
}
const prev = () => {
if(isOnUpdate) return
curLeft+=containerWidth
update()
}
const next = () => {
if(isOnUpdate) return
curLeft-=containerWidth
update()
}
return {prev,next}
}
const test = run(document.querySelector('.carousel'))
</script>