<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自动切换</title>
<style type="text/css">
.show{
width: 400px;
height: 400px;
overflow: hidden;
}
.wp{
width: 99999999999999999999999px;
height: 400px;
text-align: center;
line-height: 400px;
/*1em=816x*/
font-size: 3em;
overflow: hidden;
position: relative;
left: 0;
transition:all 0.3s;
}
.wp div{
width: 400px;
height: 400px;
text-align: center;
float: left;
line-height: 400px;
transition:all 1s;
}
/*:nth-child(n) 选择器匹配属于其父元素的第 N 个子元素,不论元素的类型。*/
.wp div:nth-child(1){
background: red;
}
.wp div:nth-child(2){
background: green;
}
.wp div:nth-child(3){
background: yellow;
}
.wp div:nth-child(4){
background: blue;
}
.btn{
width: 400px;
height: 50px;
text-align: center;
font-size: 1.5em;
line-height: 50px;
}
.btn span{
width: 100px;
height: 50px;
float: left;
text-align: center;
font-size: 1.5em;
}
.btn span:nth-child(1){
background: red;
}
.btn span:nth-child(2){
background: green;
}
.btn span:nth-child(3){
background: yellow;
}
.btn span:nth-child(4){
background: blue;
}
</style>
</head>
<body>
<div class="show">
<div class="wp" id="wp">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
</div>
</div>
<div class="btn" id="btn">
<span id="btn1">1</span>
<span id="btn2">2</span>
<span id="btn3">3</span>
<span id="btn4">4</span>
</div>
</body>
<script type="text/javascript">
var _wp = document.getElementById('wp');
var _btn = document.getElementById('btn').getElementsByTagName('span');
var m = 0;
var Ti = setInterval(function(){
m++;
if(m>=_btn.length){ //4个
m = 0;
}
_wp.style.left = -400*m + "px";
},1500)//1.5s
for(let i=0;i<_btn.length;i++){
_btn[i].onclick = function(){
clearInterval(Ti);
Ti = setInterval(function(){
m++;
if(m >=_btn.length){
m=0;
}
_wp.style.left=-400*m+"px";
},1500);
m = i;
_wp.style.left = -400*m + "px";
}
}
</script>
</html>