<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>原生js轮播图</title>
<style>
* {
margin: 0;
padding: 0;
}
#outer {
width: 400px;
height: 400px;
padding: 10px;
background-color: green;
margin: 50px auto;
position: relative;
overflow: hidden;
}
#imgUl {
list-style: none;
width: 1600px;
position: absolute;
left: 0;
}
#imgUl li {
float: left;
margin: 0 10px;
}
#nav {
position: absolute;
bottom: 20px;
}
#nav a {
float: left;
width: 15px;
height: 15px;
background-color: red;
opacity: 0.5;
margin: 0 5px;
}
</style>
<script type="text/javascript">
window.onload = function() {
var outer = document.getElementById("outer");
var imgUl = document.getElementById("imgUl");
var imgImg = document.getElementsByTagName("img");
var nav = document.getElementById("nav");
var Alla = document.getElementsByTagName("a");
imgUl.style.width = 420 * imgImg.length + "px";
nav.style.left = (outer.offsetWidth - nav.offsetWidth) / 2 + "px";
var index = 0;
Alla[0].style.backgroundColor = "black"
// 点击超链接显示对应的图片
for (var i = 0; i < Alla.length; i++) {
Alla[i].num = i;
Alla[i].onclick = function() {
//为每个超链接添加一个num属性
index = this.num;
imgUl.style.left = -420 * index + "px";
setA()
}
}
//创建方法设置选中的a链接
function setA() {
for (var i = 0; i < Alla.length; i++) {
Alla[i].style.backgroundColor = "";
}
Alla[index].style.backgroundColor = "black";
}
}
</script>
</head>
<body>
<div id="outer">
<ul id="imgUl">
<li><img src="t1.jpg" alt=""></li>
<li><img src="t2.jpg" alt=""></li>
<li><img src="t3.jpg" alt=""></li>
<li><img src="t4.jpg" alt=""></li>
</ul>
<div id="nav">
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</div>
</div>
</body>
</html>
原生js实现轮播图
最新推荐文章于 2024-07-25 09:24:40 发布