50 天学习 50 个项目 - HTMLCSS and JavaScript
day35-Image Carousel(图片轮播图简易版)
效果
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Image Carousel</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="carousel">
<div class="image-container" id="imgs">
<img src="https://images.unsplash.com/photo-1599394022918-6c2776530abb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1458&q=80"
alt="first-image" />
<img src="https://images.unsplash.com/photo-1593642632559-0c6d3fc62b89?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80"
alt="second-image" />
<img src="https://images.unsplash.com/photo-1599423300746-b62533397364?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80"
alt="third-image" />
<img src="https://images.unsplash.com/photo-1599561046251-bfb9465b4c44?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1492&q=80"
alt="fourth-image" />
</div>
<button id="left" class="btn"><</button>
<button id="right" class="btn">></button>
</div>
<script src="script.js"></script>
</body>
</html>
style.css
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
img {
width: 500px;
height: 500px;
object-fit: cover;
}
.carousel {
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
height: 500px;
width: 500px;
overflow: hidden;
position: relative;
}
.image-container {
display: flex;
transform: translateX(0);
transition: transform 0.5s ease-in-out;
}
.btn {
background-color: rgba(0, 0, 0, 0.3);
color: black;
border: none;
cursor: pointer;
width: 2rem;
outline: none;
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 0.5rem 0;
}
#left{
padding-right: 0.5rem;
border-radius: 0 50% 50% 0;
left: 0;
}
#right {
padding-left: 0.5rem;
border-radius: 50% 0 0 50%;
right: 0;
}
.btn:hover {
opacity: 0.9;
}
script.js
const imgs = document.getElementById('imgs')
const leftBtn = document.getElementById('left')
const rightBtn = document.getElementById('right')
const img = document.querySelectorAll('#imgs img')
let idx = 0
let interval = setInterval(run, 2000)
function run() {
idx++
changeImage()
}
function changeImage() {
if (idx > img.length - 1) {
idx = 0
} else if (idx < 0) {
idx = img.length - 1
}
imgs.style.transform = `translateX(${-idx * imgs.offsetWidth}px)`
imgs.style.transition = `transform 0.5s ease-in-out`
}
function resetInterval() {
clearInterval(interval)
interval = setInterval(run, 2000)
}
rightBtn.addEventListener('click', () => {
idx++
changeImage()
resetInterval()
})
leftBtn.addEventListener('click', () => {
idx--
changeImage()
resetInterval()
})