<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<style type="text/css">
*{
margin: 0;
padding:0;
}
.carousel{
margin:0 auto;
width:400px;
height: 300px;
position: relative;
}
span{
width:20px;
height:20px;
background: rgba(0,0,0,.6);
border-radius: 50%;
}
a{
text-decoration: none;
color:#fff;
}
p{
width:200px;
text-align: center;
line-height: 20px;
position: absolute;
top:260px;
left:100px;
display: flex;
justify-content: space-around;
}
</style>
<script type="text/javascript">
window.onload =function () {
var aNode = document.getElementsByTagName("a");
var divNode = document.getElementsByTagName("div")[0];
var imgNode = document.createElement("img");
for (var position in aNode) {
aNode[position].onclick = function () {
var index = this.innerText;
carousel(index);
}
}
function carousel(index) {
imgNode.src = 'images/' + index + '.jpg' + '/';
divNode.appendChild(imgNode);
}
var i = 1;
imgNode.src = 'images/' + i + '.jpg' + '/';
function change() {
imgNode.src = 'images/' + i + '.jpg' + '/';
i++;
if (i == 7) {
i = 1;
}
}
divNode.appendChild(imgNode);
setInterval(change, 1500);
}
</script>
</head>
<body>
<div class="carousel">
<p>
<span><a href="#" onclick="carousel(1)">1</a></span>
<span><a href="#" onclick="carousel(2)">2</a></span>
<span><a href="#" onclick="carousel(3)">3</a></span>
<span><a href="#" onclick="carousel(4)">4</a></span>
<span><a href="#" onclick="carousel(5)">5</a></span>
<span><a href="#" onclick="carousel(6)">6</a></span>
</p>
</div>
</body>
</html>
注意:图片需要自己去添加images文件,大小我用的是400*300,可以更改的!
还有其他方法使用js实现轮播图,比如点击以后让图片transform:translate;点击后改变其display,点击后改变z-index,不点击让他自己产生动态移动就是使用:setInterval
技术不重要,重要的是思想!