代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="tool.js"></script>
<style>
div.banner{
position: relative;
width: 700px;
height: 300px;
border: solid 3px red;
margin: 100px auto;
overflow: hidden;
}
.banner ul{
position: absolute;
margin: 0;
padding: 0;
list-style: none;
width: 3500px;
height: 300px;
background-color: pink;
}
.banner ul>li{
float: left;
width: 690px;
height: 290px;
text-align: center;
line-height: 300px;
font-size: 60px;
border: solid 5px black;
}
button{
position: absolute;
top: 140px;
}
.l{
left: 0;
}
.r{
right: 0;
}
</style>
</head>
<body>
<div class="banner">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<button class="l">←</button>
<button class="r">→</button>
<script>
var ul = document.querySelector('ul')
var lBtn = document.querySelector('.l')
var rBtn = document.querySelector('.r')
//index是当前显示图片索引
var index = 0;
lBtn.onclick = function(){
index--;
indexFn()
}
rBtn.onclick = function(){
index++;
indexFn()
}
//处理判断index(当前图片索引是否存在)
function indexFn(){
if(index<0){
index = ul.children.length-1;
}else if(index>ul.children.length-1){
index = 0;
}
console.log('接下的索引是',index);
//让图片切换
runFn()
}
//让ul移动
function runFn(){
//无动画
//ul.style.left = -index*700+'px';
//动画版
run(ul,-index*700)//移动图片长度700px
}
</script>
</div>
</body>
</html>