jquery技术实现横向轮播图
时间: 2023-12-25 14:29:08 浏览: 34
以下是使用jQuery实现横向轮播图的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>横向轮播图</title>
<style>
.bannerCon {
width: 100%;
overflow: hidden;
position: relative;
}
.bannerCon ul {
width: 300%;
position: absolute;
left: 0;
top: 0;
list-style: none;
margin: 0;
padding: 0;
}
.bannerCon ul li {
float: left;
width: 33.33%;
}
.bannerCon ul li img {
width: 100%;
height: auto;
}
.bannerCon .prev,
.bannerCon .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 30px;
height: 30px;
background-color: #ccc;
color: #fff;
text-align: center;
line-height: 30px;
cursor: pointer;
}
.bannerCon .prev {
left: 10px;
}
.bannerCon .next {
right: 10px;
}
.bannerCon .dots {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
list-style: none;
margin: 0;
padding: 0;
}
.bannerCon .dots li {
display: inline-block;
width: 10px;
height: 10px;
background-color: #ccc;
border-radius: 50%;
margin: 0 5px;
cursor: pointer;
}
.bannerCon .dots li.active {
background-color: #f00;
}
</style>
</head>
<body>
<div class="bannerCon">
<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="prev">Prev</div>
<div class="next">Next</div>
<ul class="dots">
<li class="active"></li>
<li></li>
<li></li>
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var $bannerCon = $('.bannerCon');
var $ul = $bannerCon.find('ul');
var $li = $ul.find('li');
var $prev = $bannerCon.find('.prev');
var $next = $bannerCon.find('.next');
var $dots = $bannerCon.find('.dots li');
var currentIndex = 0;
var interval;
// 切换到指定索引的图片
function goToIndex(index) {
$ul.animate({ left: -index * 100 + '%' }, 500);
$dots.removeClass('active');
$dots.eq(index).addClass('active');
currentIndex = index;
}
// 自动播放
function startAutoPlay() {
interval = setInterval(function() {
var nextIndex = (currentIndex + 1) % $li.length;
goToIndex(nextIndex);
}, 2000);
}
// 停止自动播放
function stopAutoPlay() {
clearInterval(interval);
}
// 点击上一张按钮
$prev.click(function() {
var prevIndex = (currentIndex - 1 + $li.length) % $li.length;
goToIndex(prevIndex);
});
// 点击下一张按钮
$next.click(function() {
var nextIndex = (currentIndex + 1) % $li.length;
goToIndex(nextIndex);
});
// 点击小圆点
$dots.click(function() {
var index = $(this).index();
goToIndex(index);
});
// 鼠标悬停时停止自动播放,移开时继续自动播放
$bannerCon.hover(stopAutoPlay, startAutoPlay);
// 初始化
startAutoPlay();
});
</script>
</body>
</html>
```