HTML+CSS实现全景轮播的示例代码
Sure, here is an example of how to implement a panoramic carousel using HTML and CSS:
HTML (index.html)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Panoramic Carousel</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="carousel-container">
<div class="carousel-inner">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<img src="image4.jpg" alt="Image 4">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS (style.css)
CSS
body {
margin: 0;
overflow: hidden; /* Prevent body from scrolling */
}
.carousel-container {
position: relative;
width: 100vw; /* 100% of viewport width */
height: 100vh; /* 100% of viewport height */
}
.carousel-inner {
position: absolute;
top: 0;
left: 0;
width: calc(400vw + 100%); /* Accommodate all images */
transition: transform 0.5s ease-in-out; /* Smooth transition */
}
.carousel-inner img {
display: inline-block;
width: 100%; /* Fill the entire carousel container */
height: 100%; /* Fill the entire carousel container */
object-fit: cover; /* Maintain aspect ratio and cover the entire area */
}
JavaScript (script.js)
JavaScript
let currentImageIndex = 0;
function nextImage() {
currentImageIndex++;
if (currentImageIndex >= document.querySelectorAll('.carousel-inner img').length) {
currentImageIndex = 0;
}
updateCarouselPosition();
}
function previousImage() {
currentImageIndex--;
if (currentImageIndex < 0) {
currentImageIndex = document.querySelectorAll('.carousel-inner img').length - 1;
}
updateCarouselPosition();
}
function updateCarouselPosition() {
const carouselInner = document.querySelector('.carousel-inner');
const translateXValue = -currentImageIndex * 100 + '%';
carouselInner.style.transform = `translateX(${translateXValue})`;
}
// Initial position
updateCarouselPosition();
// Add event listeners for arrow keys
document.addEventListener('keydown', function(event) {
if (event.key === 'ArrowRight') {
nextImage();
} else if (event.key === 'ArrowLeft') {
previousImage();
}
});
Explanation:
HTML:
div
) and an inner container (div
) to hold the images.<img>
element with a unique src
attribute pointing to the image source.CSS:
display: none;
initially.transform
property for a visually appealing transition between images.JavaScript:
currentImageIndex
).nextImage()
and previousImage()
to increment or decrement the currentImageIndex
and update the carousel position accordingly.updateCarouselPosition()
function updates the transform
property of the inner container to move the corresponding image into view.ArrowRight
and ArrowLeft
) to call the nextImage()
or previousImage()
functions when pressed.Key Features: