页面轮播(Carousel)是一种常见的网页设计元素,用于在有限的空间内展示多个项目(如图片、文本等),并通过自动或手动切换的方式逐个显示这些项目。
以下是一个简单的jQuery实现页面轮播的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Carousel</title>
<style>
#carousel {
width: 600px;
overflow: hidden;
position: relative;
}
#carousel-inner {
display: flex;
transition: transform 0.5s ease-in-out;
}
.carousel-item {
min-width: 100%;
box-sizing: border-box;
}
.carousel-item img {
width: 100%;
height: auto;
}
.carousel-control {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: rgba(0, 0, 0, 0.5);
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
#prev {
left: 10px;
}
#next {
right: 10px;
}
</style>
</head>
<body>
<div id="carousel">
<div id="carousel-inner">
<div class="carousel-item"><img src="image1.jpg" alt="Image 1"></div>
<div class="carousel-item"><img src="image2.jpg" alt="Image 2"></div>
<div class="carousel-item"><img src="image3.jpg" alt="Image 3"></div>
</div>
<button id="prev" class="carousel-control">Prev</button>
<button id="next" class="carousel-control">Next</button>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
let currentIndex = 0;
const items = $('.carousel-item');
const totalItems = items.length;
function showItem(index) {
const offset = -index * 100;
$('#carousel-inner').css('transform', `translateX(${offset}%)`);
}
function nextItem() {
currentIndex = (currentIndex + 1) % totalItems;
showItem(currentIndex);
}
function prevItem() {
currentIndex = (currentIndex - 1 + totalItems) % totalItems;
showItem(currentIndex);
}
$('#next').click(nextItem);
$('#prev').click(prevItem);
// Auto-play functionality
setInterval(nextItem, 3000);
});
</script>
</body>
</html>通过以上方法,可以实现一个简单且高效的页面轮播效果。