jsdongtai轮播图
时间: 2023-12-18 21:29:32 浏览: 103
以下是一个使用JavaScript实现的简单的轮播图:
```html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript轮播图</title>
<style type="text/css">
#slider {
width: 500px;
height: 300px;
position: relative;
overflow: hidden;
}
#slider img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
}
#slider img:first-child {
display: block;
}
#slider .prev, #slider .next {
position: absolute;
top: 50%;
margin-top: -20px;
font-size: 30px;
color: #fff;
cursor: pointer;
z-index: 999;
}
#slider .prev {
left: 10px;
}
#slider .next {
right: 10px;
}
</style>
</head>
<body>
<div id="slider">
<img src="img/1.jpg">
<img src="img/2.jpg">
<img src="img/3.jpg">
<img src="img/4.jpg">
<img src="img/5.jpg">
<a class="prev" href="javascript:;"><</a>
<a class="next" href="javascript:;">></a>
</div>
<script type="text/javascript">
var slider = document.getElementById('slider');
var imgs = slider.getElementsByTagName('img');
var prev = slider.getElementsByClassName('prev')[0];
var next = slider.getElementsByClassName('next')[0];
var index = 0;
var timer = null;
// 切换图片
function changeImg() {
for (var i = 0; i < imgs.length; i++) {
imgs[i].style.display = 'none';
}
imgs[index].style.display = 'block';
}
// 自动播放
function autoPlay() {
timer = setInterval(function() {
index++;
if (index >= imgs.length) {
index = 0;
}
changeImg();
}, 2000);
}
autoPlay();
// 鼠标移入停止播放,移出继续播放
slider.onmouseover = function() {
clearInterval(timer);
}
slider.onmouseout = function() {
autoPlay();
}
// 点击上一张
prev.onclick = function() {
index--;
if (index < 0) {
index = imgs.length - 1;
}
changeImg();
}
// 点击下一张
next.onclick = function() {
index++;
if (index >= imgs.length) {
index = 0;
}
changeImg();
}
</script>
</body>
</html>
```
阅读全文