思路
1.搭建好基本的样式
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 670px;
height: 300px;
margin: 100px auto;
position: relative;
overflow: hidden;
}
ul{
list-style: none;
display: flex;
}
.box>p{
width: 100%;
position: absolute;
top: 50%;
transform: translateY(-50%);
display: flex;
justify-content: space-between;
}
.box>p>span{
width: 30px;
height: 60px;
text-align: center;
line-height: 60px;
font-size: 40px;
color: #fff;
background-color: rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<div class="box">
<ul>
<li><img src="images/ad1.jpg" alt=""></li>
<li><img src="images/ad2.jpg" alt=""></li>
<li><img src="images/ad3.jpg" alt=""></li>
<li><img src="images/ad1.jpg" alt=""></li>
</ul>
<p>
<span class="left"><</span>
<span class="right">></span>
</p>
</div>
2.在头脑里构思,我到底想要什么样的效果
3.当我点击右边的按钮时,整个ul会往左移动一个img的width,当 我再次点击右边的按钮时ul总共往左了2个img的width,第三次点击后我要看到第一张img即ul往左的width是0.
4.开始编写代码,实现以上的想法
<script>
//拿到需要的元素
let oLeft=document.querySelector(".left");
let oRight=document.querySelector(".right");
let oUl=document.querySelector("ul");
let oItems=document.querySelectorAll("ul>li");
let oImag=document.querySelector("img");
let oImagWidth=parseInt(getComputedStyle(oImag).width);
//设置一开始的值
let current=0;
//监听按钮
oRight.onclick=function () {
//点击一下,current不就是1了吗,第二次不就是2了吗
current++;
//判断是否点击了三下
if(current>oItems.length-1){
current=0;
oUl.style.marginLeft=-oImagWidth*current+"px";
// current++;
}
oUl.style.marginLeft=-oImagWidth*current+"px";
// linerAnimation(oUl,-oImagWidth*current);
console.log(oUl.style.marginLeft);
};
4.如果想要做缓冲运动的话,直接复制缓冲运动的方法就行了
5.检查是否有bug
6.发现还真有,吐血ing.吐完之后回来解决问题.当我们点击右键第三下是会非常生硬的跳到第一张图片.我们的想法是缓慢的到第一张.然后在缓慢的到第二张,可以第三张图片后面直接添加第一张的图片,然后直接直接跳到第一张(因为是一样的图片直接移到第一张,人眼根本不能发现.计算机老快了,哈哈哈),再缓慢的移到动第二张.
7.看代码
oRight.onclick=function () {
//点击一下,current不就是1了吗,第二次不就是2了吗
current++;
//判断是否点击了三下
if(current>oItems.length-1){
current=0;
oUl.style.marginLeft=-oImagWidth*current+"px";
current++;
}
console.log(oImagWidth * current);
// oUl.style.marginLeft=-oImagWidth*current+"px";
linerAnimation(oUl,-oImagWidth*current);
console.log(oUl.style.marginLeft);
};