原生javascript简单轮播效果demo

本文介绍了一个使用纯 JavaScript 实现的轮播图效果案例,包括自动播放、鼠标悬停暂停及指示器导航功能。通过 CSS 样式控制轮播图的外观,利用 JavaScript 控制轮播图的逻辑,实现了平滑过渡和良好的用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!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.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++;
}
}

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值