html实现焦点轮播图
时间: 2023-12-07 16:04:24 浏览: 117
以下是使用HTML、CSS和JavaScript实现焦点轮播图的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>焦点轮播图</title>
<style>
/* 轮播图容器 */
#slider {
width: 600px;
height: 300px;
margin: 0 auto;
position: relative;
overflow: hidden;
}
/* 图片容器 */
#slider .slider-img {
width: 6000px;
height: 300px;
position: absolute;
left: 0;
top: 0;
}
/* 图片 */
#slider .slider-img img {
float: left;
width: 600px;
height: 300px;
}
/* 箭头 */
#slider .slider-arrow {
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: 24px;
cursor: pointer;
}
#slider .slider-arrow.prev {
left: 0;
}
#slider .slider-arrow.next {
right: 0;
}
/* 按钮 */
#slider .slider-btn {
position: absolute;
bottom: 20px;
left: 50%;
margin-left: -75px;
z-index: 1;
}
#slider .slider-btn span {
display: inline-block;
width: 10px;
height: 10px;
margin: 0 5px;
background-color: #fff;
border-radius: 50%;
cursor: pointer;
}
#slider .slider-btn span.active {
background-color: #f00;
}
</style>
</head>
<body>
<div id="slider">
<div class="slider-img">
<img src="img/1.jpg" alt="">
<img src="img/2.jpg" alt="">
<img src="img/3.jpg" alt="">
<img src="img/4.jpg" alt="">
<img src="img/5.jpg" alt="">
<img src="img/6.jpg" alt="">
</div>
<div class="slider-arrow prev"><</div>
<div class="slider-arrow next">></div>
<div class="slider-btn">
<span class="active"></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<script>
// 获取元素
var slider = document.getElementById('slider');
var sliderImg = slider.getElementsByClassName('slider-img')[0];
var sliderImgs = sliderImg.getElementsByTagName('img');
var sliderArrow = slider.getElementsByClassName('slider-arrow');
var sliderBtn = slider.getElementsByClassName('slider-btn')[0];
var sliderBtns = sliderBtn.getElementsByTagName('span');
// 定义变量
var index = 0; // 当前显示的图片索引
var timer = null; // 定时器
// 上一张
sliderArrow[0].onclick = function() {
index--;
if (index < 0) {
index = sliderImgs.length - 1;
}
changeImg();
}
// 下一张
sliderArrow[1].onclick = function() {
index++;
if (index >= sliderImgs.length) {
index = 0;
}
changeImg();
}
// 切换图片
function changeImg() {
// 切换图片
for (var i = 0; i < sliderImgs.length; i++) {
sliderImgs[i].style.display = 'none';
}
sliderImgs[index].style.display = 'block';
// 切换按钮
for (var i = 0; i < sliderBtns.length; i++) {
sliderBtns[i].className = '';
}
sliderBtns[index].className = 'active';
}
// 切换按钮
for (var i = 0; i < sliderBtns.length; i++) {
sliderBtns[i].index = i;
sliderBtns[i].onclick = function() {
index = this.index;
changeImg();
}
}
// 自动播放
function autoPlay() {
timer = setInterval(function() {
index++;
if (index >= sliderImgs.length) {
index = 0;
}
changeImg();
}, 2000);
}
autoPlay();
// 鼠标移入停止播放,移出继续播放
slider.onmouseover = function() {
clearInterval(timer);
}
slider.onmouseout = function() {
autoPlay();
}
</script>
</body>
</html>
```
阅读全文