<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>轮播图换背景</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.bg{
width: 1000px;
height: 500px;
border: 1px solid black;
margin: 0px auto;
position: relative;
overflow: hidden;
}
.img{
width: 4000px;
height: 500px;
transition: all 1s;
}
.img div{
width: 1000px;
height: 500px;
float: left;
}
.button{
position: absolute;
width: 50px;
height: 100px;
background-color: darkgray;
top: 0px;
bottom: 0px;
margin: auto;
}
.right{
right: 0px;
}
.span{
width: 100%;
height: 50px;
position: absolute;
bottom: 0px;
text-align: center;
}
.span span{
width: 20px;
height: 20px;
background-color:white;
display: inline-block;
border-radius: 20px;
margin: 10px 10px;
}
button{
display: block;
margin: 10px auto;
}
.span .cur{/*.span必须加,关于类名的约分优先级高低,点击时触发的样式*/
background-color: red;
}
</style>
</head>
<body>
<div class="bg">
<div class="img">
<div style="background-color: lightblue;"></div>
<div style="background-color: lightcoral;"></div>
<div style="background-color: lightgray;"></div>
<div style="background-color: lightgreen;"></div>
</div>
<div class="button left"></div>
<div class="button right"></div>
<div class="span">
<span class="cur"></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<button>点击收起</button>
</body>
<script type="text/javascript">
var left=document.querySelector('.left');
var right=document.querySelector('.right');
var box=document.querySelector('.img');
var img=document.querySelectorAll('.img div');
var span=document.querySelectorAll('.span span');
var btn=document.querySelector('button');
var bg=document.querySelector('.bg');
var num=0;//用来记录轮播图上的左右按钮被点击的次数
var ga=0//用来记录展开收起按钮被点击的次数
right.onclick=function()//右按钮点击事件
{
num++;
if(num>=4)
{
num=0;
}
for(var y=0;y<span.length;y++)
{
span[y].className='';
}
span[num].className='cur';
box.style.marginLeft=-1000*num+'px';
}
left.onclick=function()//左按钮点击事件
{
num--;
if(num<=-1)
{
num=3;
}
for(var y=0;y<span.length;y++)
{
span[y].className='';
}
span[num].className='cur';
box.style.marginLeft=-1000*num+'px';
}
for(var x=0;x<img.length;x++)//换背景点击事件
{
img[x].onclick=function()
{
document.body.style.backgroundColor=this.style.backgroundColor;//如果是换背景图片,需要将图片设置为background(背景图片)样式
}
}
btn.onclick=function()//盒子点击展开收起事件
{
if(ga%2==0)//判断盒子展开收起按钮被点击的次数是哪一次
{
bg.style.height='0px';//盒子收起状态
btn.innerHTML='点击展开';
}
else
{
bg.style.height='500px';//盒子展开状态
btn.innerHTML='点击收起';
}
ga++;
}
for(var x=0;x<span.length;x++)//小圆点点击
{
span[x].a=x;//获取每一个小圆点的下标
span[x].onclick=function()
{
for(var y=0;y<span.length;y++)
{
span[y].className='';
}
this.className='cur';
box.style.marginLeft=-1000*this.a+'px';//this.a就表示小圆点的下标
num=this.a;//将小圆点的点击与总点击次数进行绑定
}
}
</script>
</html>