tab切换效果 网站中的图片自动切换

时间:2023-03-09 09:44:20
tab切换效果  网站中的图片自动切换

网站中的图片自动切换

今天上一套tab切换效果的代码
tab切换效果  网站中的图片自动切换
tab切换效果  网站中的图片自动切换
tab切换效果  网站中的图片自动切换
tab切换效果  网站中的图片自动切换
tab切换效果  网站中的图片自动切换

动图就自己实现吧!
下面贴HTML代码,大体分两部分,图片div和按钮div,代码很容易看懂~

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<script type="text/javascript" src="indexpic.js"></script>
<link rel="stylesheet" type="text/css" href="indexpic.css">
</head>
<body>
<div id="main" class="main">
<div id="pic" class="pic">
<div id="pictures" class="pictures"> <div id="p1" class="p" style="display: block;background-color: red">
<!-- <img src="img/1.jpg"> -->
</div>
<div id="p2" class="p" style="display: none;background-color: yellow">
<!-- <img src="img/2.jpg"> -->
</div>
<div id="p3" class="p" style="display: none;background-color: blue">
<!-- <img src="img/3.jpg"> -->
</div>
<div id="p4" class="p" style="display: none;background-color: green">
<!-- <img src="img/4.jpg"> -->
</div>
<div id="p5" class="p" style="display: none;background-color: pink">
<!-- <img src="img/5.jpg"> -->
</div> </div>
<div class="btn">
<button style="background: #ed6911;">1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
</div>
</div>
</div>
</body>
</html>

这个还是比较简单的div结构,下面是对应的css代码

button{
background: none;
border: 1px solid black;
}
.btn{
margin-top: -35px;
padding-left: 340px;
}
.p{
width: 100%;
height: 170px
}
#main{
width: 490px;
height: 280px;
margin: 0 auto;
}
#pictures{
height: 170px;
width: 100%;
margin-top: 110px;
}

对所有div的简单布局,最后主要实现功能~所以重要的js代码如下:

window.onload=tab;

function tab(){
//定义索引和定时器
var index=0;
var timer=null;
//获取按钮和div的个数
var bt=document.getElementsByTagName('button');
var divs=document.getElementsByClassName('p');
//设定mouseover和mouseout事件
for(var i=0;i<bt.length;i++){
bt[i].id=i;
bt[i].onmouseover=function(){
clearInterval(timer);
changeOption(this.id);
}
bt[i].onmouseout=function(){
timer=setInterval(autoPlay,2000);
}
}
//清除和设置定时器
if(timer){
clearInterval(timer);
timer=null;
}
timer=setInterval(autoPlay,2000);
//自动播放函数
function autoPlay(){
index++;
if(index>=bt.length){
index=0;
}
changeOption(index);
}
//获取当前button索引值
function changeOption(curIndex){
for(var j=0;j<bt.length;j++){
bt[j].style.background='none';
divs[j].style.display='none';
}
bt[curIndex].style.background='#ed6911';
divs[curIndex].style.display='block';
index=curIndex;
}
}