JavaScript基础学习笔记之轮播
轮播效果:

轮播效果图
index.html文件内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>轮播图</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div id="box">
<img src="img/1.jpg" id="pic"/>
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
</ul>
<div id="left" class="bt"><</div>
<div id="right" class="bt">></div>
</div>
</body>
<script type="text/javascript" src="js/loop.js"></script>
</html>
loog.js文件内容
var jsBox = document.getElementById("box")
var jsPic = document.getElementById("pic")
var jsLeft = document.getElementById("left")
var jsRight = document.getElementById("right")
var jsLisArr = document.getElementsByTagName("li")
//第一个li设置为红色
jsLisArr[0].style.backgroundColor = "red"
//启动一个定时器去更换jsPic中的src属性
var currentPage = 1
var timer = setInterval(startLoop, 1000)
function startLoop(){
currentPage++
changePage()
}
function changePage(){
if (currentPage == 9){
currentPage = 1
} else if (currentPage == 0){
currentPage = 8
}
jsPic.src = "img/" + currentPage + ".jpg"
//清空所有小圆点的颜色
for (var i = 0; i < jsLisArr.length; i++){
jsLisArr[i].style.backgroundColor = "#aaa"
}
jsLisArr[currentPage - 1].style.backgroundColor = "red"
}
//鼠标进入box
jsBox.addEventListener("mouseover", overFunc, false)
function overFunc(){
//停止定时器
clearInterval(timer)
//显示左右按钮
jsLeft.style.display = "block"
jsRight.style.display = "block"
}
jsBox.addEventListener("mouseout", outFunc, false)
function outFunc(){
//重启定时器
timer = setInterval(startLoop,1000)
//隐藏左右按钮
jsLeft.style.display = "none"
jsRight.style.display = "none"
}
//点击左右按钮
jsLeft.addEventListener("mouseover", deep, false)
jsRight.addEventListener("mouseover", deep, false)
function deep(){
this.style.backgroundColor = "rgba(0,0,0,0.6)"
}
jsLeft.addEventListener("mouseout", nodeep, false)
jsRight.addEventListener("mouseout", nodeep, false)
function nodeep(){
this.style.backgroundColor = "rgba(0,0,0,0.2)"
}
jsRight.addEventListener("click", function(){
currentPage++
changePage()
}, false)
jsLeft.addEventListener("click", function(){
currentPage--
changePage()
}, false)
//进入小圆点
for (var i = 0; i < jsLisArr.length; i++){
jsLisArr[i].index = i + 1
jsLisArr[i].addEventListener("mouseover", function(){
// currentPage = parseInt(this.innerHTML)
currentPage = parseInt(this.index)
changePage()
},false)
}
style.css文件内容
*{
padding: 0;
margin: 0;
}
#box{
width: 790px;
height: 340px;
margin: 0 auto;
position: relative;
}
.bt{
width: 50px;
height: 80px;
background-color: rgba(0,0,0,0.2);
color: #fff;
font-size: 30px;
line-height: 80px;
text-align: center;
position: absolute;
top: 130px;
display: none;
}
#left{
left: 0;
}
#right{
right: 0;
}
#list{
list-style: none;
position: absolute;
bottom: 20px;
left: 250px;
}
#list li{
float: left;
width: 20px;
height: 20px;
background-color: #aaa;
margin-left: 10px;
border-radius: 50%;
text-align: center;
line-height: 20px;
}
几张轮播图如下
1.jpg
2.jpg
3.jpg
4.jpg
5.jpg
6.jpg
7.jpg
8.jpg
网友评论