您的位置:首页 > Web前端 > JavaScript

原生javascript简单轮播效果demo

2017-03-05 13:13 351 查看
<!DOCTYPE html>

<html>
<head>
<title>demo</title>
<style>
span{padding:5px 10px; background:blue;margin-bottom:5px;}
.box{width:300px;height:100px;overflow:hidden;}
.box div{width:300px;height:100px; display:none;}
.box .block{display:block;}
#status .active{background:#ccc;}
</style>
<script>
window.onload = function(){
function BannerToggle(time, obj){

var time = time;
//循环时间
var box = document.querySelector(obj);
var count = 1;
var timeId = null;
var status = document.querySelectorAll('#status span');

function autoPlay(){
if(count <= 3){
box.querySelector('.block').className = box.querySelector('.block').className.replace('block','');
box.querySelectorAll('div')[count].className = 'block';
document.querySelector('#status .active').className = document.querySelector('#status .active').className.replace('active','');
status[count].className = 'active';
count++;
}else{
count = 0;
box.querySelector('.block').className = box.qu
4000
erySelector('.block').className.replace('block','');
box.querySelectorAll('div')[count].className = 'block';
document.querySelector('#status .active').className = document.querySelector('#status .active').className.replace('active','');
status[count].className = 'active';
count++;
}
}

this.init = function(){
timeID = setInterval(autoPlay,time);
for(var i = 0; i < status.length; i++ ){
(function(j){
console.log(j);
status[j].onmouseenter = function(){
clearInterval(timeID);
count = j;
console.log(count);
box.querySelector('.block').className = box.querySelector('.block').className.replace('block','');
box.querySelectorAll('div')[count].className = 'block';
document.querySelector('#status .active').className = document.querySelector('#status .active').className.replace('active','');
status[count].className = 'active';
}
status[j].onmouseleave = function(){
count++;
timeID = setInterval(autoPlay,time);
}
})(i);
}
}
this.init();
}

var a = new BannerToggle(3000, '.box');
}

</script>
</head>
<body>
<div style="padding:10px 0;" id="status">
<span class="active">1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
<div class="box">
<div style="background:red;" class="block"></div>
<div style="background:#ccc;"></div>
<div style="background:green;"></div>
<div style="background:yellow;"></div>
</div>
<div style="width:100px;height:100px;padding:100px;margin:100px;background:#000;">
</body>

</html>

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: