jQuery图片轮播
时间: 2023-12-09 20:36:45 浏览: 146
以下是一个简单的jQuery图片轮播的例子,其中使用了时间阀来控制图片的滚动速度,并且添加了左右按钮来控制图片的滚动方向和速度:
```html
<!DOCTYPE html>
<html>
<head>
<title>jQuery图片轮播</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style type="text/css">
#slider {
width: 600px;
height: 400px;
margin: 0 auto;
position: relative;
overflow: hidden;
}
#slider img {
width: 600px;
height: 400px;
position: absolute;
top: 0;
left: 0;
display: none;
}
#slider img:first-child {
display: block;
}
#slider .prev, #slider .next {
position: absolute;
top: 50%;
margin-top: -20px;
width: 40px;
height: 40px;
background-color: #fff;
border-radius: 50%;
text-align: center;
line-height: 40px;
font-size: 24px;
color: #333;
cursor: pointer;
opacity: 0.5;
transition: opacity 0.3s ease-in-out;
}
#slider .prev:hover, #slider .next:hover {
opacity: 1;
}
#slider .prev {
left: 20px;
}
#slider .next {
right: 20px;
}
</style>
</head>
<body>
<div id="slider">
<img src="img/1.jpg" alt="图片1">
<img src="img/2.jpg" alt="图片2">
<img src="img/3.jpg" alt="图片3">
<img src="img/4.jpg" alt="图片4">
<img src="img/5.jpg" alt="图片5">
<a href="javascript:;" class="prev"><</a>
<a href="javascript:;" class="next">></a>
</div>
<script type="text/javascript">
$(function() {
var $slider = $('#slider');
var $img = $slider.find('img');
var len = $img.length;
var index = 0;
var interval = 3000; // 时间阀,控制图片滚动速度
var timer;
// 左右按钮点击事件
$slider.on('click', '.prev', function() {
index--;
if (index < 0) {
index = len - 1;
}
showImg(index);
}).on('click', '.next', function() {
index++;
if (index >= len) {
index = 0;
}
showImg(index);
});
// 显示图片
function showImg(index) {
$img.eq(index).fadeIn().siblings().fadeOut();
}
// 自动轮播
function autoPlay() {
timer = setInterval(function() {
index++;
if (index >= len) {
index = 0;
}
showImg(index);
}, interval);
}
autoPlay();
// 鼠标移入停止轮播,移出继续轮播
$slider.hover(function() {
clearInterval(timer);
}, function() {
autoPlay();
});
});
</script>
</body>
</html>
```
阅读全文