JavaScript_banner轮播图
让我们一起来学习一下用js怎么实现banner轮播图呢?
直接看代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>banner轮播</title>
<style>
#banner{width:820px;height:430px;margin:0 auto;position:relative;}
#banner img{width:100%;height:100%;}
ul{position:absolute;top:83%;left:290px;list-style:none;}
ul li{width:25px;height:25px;border-radius:50%;float:left;margin-right:15px;text-align:center;line-height:25px;}
#Left,#Right{position:absolute;top:45%;width:60px;height:60px;display:none;}
#banner:hover #Left{display:block;}
#banner:hover #Right{display:block;}
#Left{left:0;}
#Right{right:0;}
</style>
</head>
<!--页面加载的时候直接加载它-->
<body onload="lunbo()">
<div id="banner">
<img src="img/banner0.jpg" id="img">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<div id="Left">
<img src="img/07_箭头_向左.png" id="left">
</div>
<div id="Right">
<img src="img/07_箭头_向右 (1).png" id="right">
</div>
</div>
<script type="text/javascript">
//首先我们要获取到他们,便于接下来操作
var Img=document.getElementById("img");
var Lis=document.getElementsByTagName("li");
var Left=document.getElementById("left");
var Right=document.getElementById("right");
var index=-1;
var Banner=document.getElementById("banner");
//定时器(需要定义的函数,它的毫秒数)
var timer=setInterval("lunbo()",1800);
//利用定时器使图片达到轮播效果
function lunbo(){
index++;
resetColor();
if(index == 4){
index=0;
}
Img.src="img/banner"+index+".jpg";
Lis[index].style.background="orchid";
}
//小原点初始值颜色(定义函数,在定时器去调用它)
function resetColor(){
for(var i=0;i<Lis.length;i++){
Lis[i].style.background="rgba(100,100,100,.5)";
}
}
//鼠标移入和移出
Banner.onmouseover=function(){
clearInterval(timer);
}
Banner.onmouseout=function(){
//变量作用域,因为这边已经给它清除了,所以必须重新声明它.
timer=setInterval("lunbo()",1800);
}
//点击小圆点切换图片到指定位置
for (var i=0;i<Lis.length;i++) {
Lis[i].onclick = function(){
clearInterval(timer);
index = this.innerHTML-1;
Img.src="img/banner"+index+".jpg";
resetColor();
Lis[index].style.background = "orchid";
timer = setInterval("lunbo()",1800);
}
}
//左边和右边按钮切换
Left.onclick = function(){
index--;
if (index == -1) {
index = 3;
}
Img.src="img/banner"+index+".jpg";
resetColor();
Lis[index].style.background = "orchid";
}
Right.onclick = function(){
if (index == 3) {
index = -1;
}
index++;
Img.src="img/banner"+index+".jpg";
resetColor();
Lis[index].style.background = "orchid";
}
</script>
</body>
</html>
希望对大家有帮助~~如果有更好的方法,可以一起学习交流哦!