html焦点图轮播图代码
时间: 2023-12-03 20:40:45 浏览: 106
以下是一个基于jQuery实现的HTML焦点图轮播代码,支持自动轮播与手动点击:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>焦点图轮播</title>
<style type="text/css">
#slider {
width: 600px;
height: 300px;
margin: 0 auto;
position: relative;
overflow: hidden;
}
#slider img {
width: 600px;
height: 300px;
position: absolute;
top: 0;
left: 0;
display: none;
}
#slider img.active {
display: block;
}
#slider .btn {
position: absolute;
top: 50%;
margin-top: -20px;
width: 40px;
height: 40px;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
text-align: center;
line-height: 40px;
font-size: 20px;
cursor: pointer;
opacity: 0.5;
transition: opacity 0.3s;
}
#slider .btn:hover {
opacity: 1;
}
#slider .prev {
left: 0;
}
#slider .next {
right: 0;
}
#slider .dots {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 1;
}
#slider .dots span {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #fff;
margin: 0 5px;
cursor: pointer;
opacity: 0.5;
transition: opacity 0.3s;
}
#slider .dots span.active {
opacity: 1;
}
</style>
</head>
<body>
<div id="slider">
<img src="img/1.jpg" alt="1" class="active">
<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">
<div class="btn prev"><</div>
<div class="btn next">></div>
<div class="dots">
<span class="active"></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
var $slider = $('#slider');
var $imgs = $slider.find('img');
var $btnPrev = $slider.find('.prev');
var $btnNext = $slider.find('.next');
var $dots = $slider.find('.dots span');
var len = $imgs.length;
var index = 0;
var timer;
// 显示当前图片和小圆点
function show() {
$imgs.filter('.active').fadeOut().removeClass('active');
$imgs.eq(index).fadeIn().addClass('active');
$dots.eq(index).addClass('active').siblings().removeClass('active');
}
// 自动轮播
function autoPlay() {
timer = setInterval(function() {
index++;
if (index === len) {
index = 0;
}
show();
}, 2000);
}
autoPlay();
// 鼠标悬停停止轮播,离开继续轮播
$slider.hover(function() {
clearInterval(timer);
}, function() {
autoPlay();
});
// 点击小圆点切换图片
$dots.click(function() {
index = $(this).index();
show();
});
// 点击左右箭头切换图片
$btnPrev.click(function() {
index--;
if (index === -1) {
index = len - 1;
}
show();
});
$btnNext.click(function() {
index++;
if (index === len) {
index = 0;
}
show();
});
});
</script>
</body>
</html>
```
阅读全文