js实现轮播图效果(附源码)--原生js的应用

1.js实现轮播图效果

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Author" content="奇客艺术">
<meta name="keyword" content="关键字">
<meta name="description" content="描述">
<title>js实现轮播图效果</title>
<style type="text/css">
*{margin: 0;padding: 0;}
#box{width: 1024px;height: 280px;margin: 0 auto;position: relative;overflow: hidden}
#box ul{width:6144px;margin-left: 0;transition: 0.2s;}/*transition为css3属性实现过渡效果*/
#box ul li{list-style-type: none;width: 1024px;height: 280px;float: left}
#box .btn #left,#box .btn #right{width: 30px;height: 40px;background: rgba(0,0,0,.4);position: absolute;top: calc(50% - 20px);cursor: pointer; }
#left{left: 0;}
#right{right: 0;}
#box .btn #left img,#box .btn #right img {width: 100%;height: 100%}
#box #nav{position: absolute;left: calc(50% - 43px);bottom:10px;width:86px;height: 10px;}
#box #nav span{background:#cccccc;width: 10px;height: 10px;float: left;border-radius: 50%;margin-left: 6px;cursor: pointer}
#box #nav .on{background: #f50}
</style>
</head>
<body>
<div id="box">
<ul>
<li><img src="images/1.jpg"></li>
<li><img src="images/2.jpg"></li>
<li><img src="images/3.jpg"></li>
<li><img src="images/4.jpg"></li>
<li><img src="images/5.jpg"></li>
</ul>
<div class="btn">
<div id="left"><img src="images/left.png"></div>
<div id="right"><img src="images/right.png"></div>
</div>
<div id="nav">
<span class="on"></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<script language="JavaScript">
var oSpan=document.getElementsByTagName('span');
var oUL=document.getElementsByTagName('ul')[0];//获取ul标签
var oBtn=document.getElementsByClassName('btn')[0];
var oDiv=oBtn.getElementsByTagName('div');
var oBox=document.getElementById('box');
var index=0;
var number=0;
var timer;//定义定时器变量
play();
for(var i=0;i<oSpan.length;i++){
oSpan[i].nxl=i;//自定义属性 i=0,1,2,3,4
oSpan[i].onclick=function () {
oSpan[index].className='';//index初始为0,将第一个span属性清空,即去掉了on里的属性
index=this.nxl;//保存获取的被点击的序列号
this.className='on';
oUL.style.marginLeft=-1024*index+'px';
}
}
//点击按钮实现图片变换
for(var j=0;j<oDiv.length;j++){
oDiv[j].nxl=j;
oDiv[j].onclick=function () {
number=this.nxl;
oSpan[index].className='';
if (number){
index++;
if(index>4) {
index=0;
}
}else {index--;
if (index<0){
index=4;
}
}
oSpan[index].className='on';
oUL.style.marginLeft=-1024*index+'px';
}
}
//鼠标滑在id为box的div上
oBox.onmouseover = function () {
clearInterval(timer);
}
//鼠标滑出id为box的div
oBox.onmouseout = function () {//onmouseleave同onmouseout 鼠标滑出
play();//调用play函数
}
//使用定时器实现图片自动变换
function play() {
timer = setInterval(function () {
oSpan[index].className='';
index++;
if(index>4){index=0;}
oSpan[index].className='on';
oUL.style.marginLeft = -1024*index+'px';
},2000)//每2秒执行一次
}
</script>
</body>
</html>

2.效果图

 

源码:js实现轮播图效果.zip

备注:

  文章为本人原创  转载请注明出处  文章难免会有纰漏之处  还望大家多多包含  如有意见或者建议可与本人联系  本人QQ:2187093468(非诚请勿扰,加好友请备注在哪里看到的)

posted @ 2017-07-31 23:18  牛新龙的IT技术博客  阅读(776)  评论(0编辑  收藏  举报