index.html
<body>
<section class="carousel">
<div class="carousel-slider">
<ul class="carousel-list">
<li class="carousel-item">
<img src="" />
</li>
<li class="carousel-item">
<img src="" />
</li>
<li class="carousel-item">
<img src="" />
</li>
<li class="carousel-item">
<img src="" />
</li>
<li class="carousel-item">
<img src="" />
</li>
<li class="carousel-item">
<img src="" />
</li>
<li class="carousel-item">
<img src="" />
</li>
</ul>
</div>
</section>
<script src="app.js"></script>
</body>
style.css
*{
margin:0;
padding:0;
box-sizing: border-box;
}
body{
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
ul{
margin:0;
padding:0;
list-style: none;
}
.carousel{
position:relative;
overflow:hidden;
width: 80vw;
height:200px;
}
.carousel-list{
position: absolute;
width:100%;
top:50%;
left:0;
transform: translate(0,-50%);
display:flex;
align-items: center;
justify-content: space-around;
}
.carousel-item{
display:flex;
align-items: center;
justify-content: center;
width: 200px;
height:200px;
padding:0 30px;
cursor: pointer;
}
.carousel-item:hover{
transform: scale(1.1);
font-size: 30px;
}
img{
width: 100%;
object-fit: cover;
}
app.js
const carousel = () => {
let carouselSlider = document.querySelector('.carousel-slider');
let list = document.querySelector('.carousel-list');
let item = document.querySelector('.carousel-item');
let list2;
const speed = 1;
const width = list.offsetWidth;
let x = 0;
let x2 = width;
const clone = () => {
list2 = list.cloneNode(true)
carouselSlider.appendChild(list2)
list2.style.left = `${width}px`;
}
const moveFirst = () => {
x -= speed;
if(width >= Math.abs(x)){
list.style.left = `${x}px`
}else{
x = width
}
}
const moveSecond = () => {
x2 -= speed;
if(list2.offsetWidth >= Math.abs(x2)){
list2.style.left = `${x2}px`
}else{
x2 = width;
}
}
const hover = () => {
clearInterval(a);
clearInterval(b);
}
const unHover = () => {
a = setInterval(moveFirst, 10)
b = setInterval(moveSecond, 10)
}
clone()
let a = setInterval(moveFirst, 10);
let b = setInterval(moveSecond, 10);
carouselSlider.addEventListener('mouseenter', hover)
carouselSlider.addEventListener('mouseleave', unHover)
}
carousel();
cloneNode
똑같은 노드를 복제하여 만들 수 있는 방법