以下是一个使用 jQuery 实现的左右箭头控制焦点图自动轮播的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>焦点图自动轮播</title>
<style>
* {
margin: 0;
padding: 0;
}
.slider {
position: relative;
width: 80%;
margin: 0 auto;
overflow: hidden;
}
.slider ul {
display: flex;
list-style: none;
}
.slider ul li {
width: 100%;
transition: all 0.5s;
}
.slider .arrow {
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}
.slider .prev {
left: 10px;
}
.slider .next {
right: 10px;
}
</style>
</head>
<body>
<div class="slider">
<ul>
<li><img src="image1.jpg" alt="Image 1"></li>
<li><img src="image2.jpg" alt="Image 2"></li>
<li><img src="image3.jpg" alt="Image 3"></li>
</ul>
<div class="arrow prev">❮</div>
<div class="arrow next">❯</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
let currentIndex = 0;
const $sliderUl = $('.slider ul');
const $slides = $sliderUl.find('li');
const slideCount = $slides.length;
function moveToSlide(index) {
$sliderUl.css('transform', `translateX(-${index * 100}%)`);
currentIndex = index;
}
$('.prev').click(function () {
let newIndex = currentIndex - 1;
if (newIndex < 0) {
newIndex = slideCount - 1;
}
moveToSlide(newIndex);
});
$('.next').click(function () {
let newIndex = currentIndex + 1;
if (newIndex >= slideCount) {
newIndex = 0;
}
moveToSlide(newIndex);
});
// 自动轮播
setInterval(function () {
let newIndex = currentIndex + 1;
if (newIndex >= slideCount) {
newIndex = 0;
}
moveToSlide(newIndex);
}, 3000);
});
</script>
</body>
</html>
基础概念:
优势:
类型:
应用场景:
常见问题及解决方法:
希望这个示例和解释能帮助您理解并实现焦点图的自动轮播功能。
领取专属 10元无门槛券
手把手带您无忧上云