JSFiddle - React, Tailwind, and code Playground
by kulimusoda
HTML
<section>
<div class="carousel">
<button class="carousel-btn prev"><</button>
<button class="carousel-btn next">></button>
<ul class="slides">
<li class="slide active">
<img src="https://images.unsplash.com/photo-1468581264429-2548ef9eb732?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80" alt="sea">
</li>
<li class="slide">
<img src="https://images.unsplash.com/photo-1439405326854-014607f694d7?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80" alt="sea">
</li>
<li class="slide">
<img src="https://images.unsplash.com/photo-1457195740896-7f345efef228?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80" alt="sea">
</li>
<li class="slide">
<img src="https://images.unsplash.com/photo-1559128010-7c1ad6e1b6a5?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1173&q=80" alt="sea">
</li>
<li class="slide">
<img src="https://images.unsplash.com/photo-1530053969600-caed2596d242?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1074&q=80" alt="sea">
</li>
</ul>
</div>
</section>
SCSS
*, *::before, *::after {
box-sizing: border-box;
}
.carousel {
height: 100vh;
width: 100vw;
position: relative;
&-btn {
position: absolute;
background: none;
border: none;
top: 50%;
transform: translateY(-50%);
z-index: 2;
font-size: 3rem;
color: rgba(255, 255, 255, 0.5);
cursor: pointer;
border-radius: 0.25rem;
padding: 0 0.5rem;
background-color: rgba(0, 0, 0, 0.1);
&:hover,
&:focus {
color: #fff;
background-color: rgba(0, 0, 0, 0.2);
}
&:focus {
outline: 1px solid #000;
}
&.prev {
left: 1rem;
}
&.next {
right: 1rem;
}
}
.slide {
inset: 0;
opacity: 0;
position: absolute;
transition: 0.2s opacity ease-in-out;
transition-delay: 0.2s;
overflow: hidden;
& > img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
&.active {
opacity: 1;
transition-delay: 0s;
z-index: 1;
}
}
}
JavaScript
const buttons = document.querySelectorAll('.carousel-btn');
function control() {
const slides = document.querySelector('.slides');
const active = document.querySelector('.active');
const offset = event.target.className.includes('next') ? 1 : -1;
let newIndex = [...slides.children].indexOf(active) + offset;
if (newIndex < 0) newIndex = slides.children.length - 1;
if (newIndex >= slides.children.length) newIndex = 0;
console.log(slides.children[2]);
slides.children[newIndex].classList.add('active');
active.classList.remove('active');
}
for (let button of buttons) {
button.onclick = control;
}
const arr = [1,2,3,4,5];
let newArr = [...arr];
for(let item of newArr){
console.log(`這是:${item}`);
}