html:
<div class="container"> <!-- 无缝轮播-->
<div class="carousel-image" style="left: -500px;">
<img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=339056085,2254279736&fm=27&gp=0.jpg" class="image">
<img src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1465757463,2243826297&fm=27&gp=0.jpg" class="image">
<img src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=836142732,2789906085&fm=27&gp=0.jpg" class="image">
<img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=339056085,2254279736&fm=27&gp=0.jpg" class="image">
<img src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1465757463,2243826297&fm=27&gp=0.jpg" class="image">
</div>
<div style="position: absolute;top: 150px;width: 500px;display: flex;justify-content: space-between;color:white;">
<span id="pre">pre</span>
<span id="next">next</span>
</div>
</div>
css:
.container{
position: relative;
width:500px;
height: 330px;
overflow: hidden;
}
.carousel-image{
position: absolute;
width:3000px;
}
js:
let pre = document.getElementById("pre");
let next = document.getElementById("next");
let carouselImage = document.getElementsByClassName("carousel-image");
console.log(carouselImage[0].style.left) //注意了:.style.left只能获取有内联样式的标签的left,否则为空。.offsetLeft才可以获取标签的left
//向右滑动
next.onclick = function () {
animate(-500);
}
pre.onclick = function () {
animate(500);
}
//移动函数
function animate(offset){ //为什么第二次go()函数调用时,offset为NaN
var leftDistance = parseInt(carouselImage[0].style.left) + offset;
var newoffset = offset;
var speed = newoffset/20; //注意:如果这行代码放在go()函数里面,go()第二次执行的时候newoffset为NaN,导致定时器失效。应该是涉及到了作用域链的知识点。 每一步移动的距离 speed>0是向右
//动画函数
function go(newoffset){
currentLeft = carouselImage[0].style.left; //当前图片的位置
if(speed > 0 && leftDistance > parseInt(currentLeft) || speed < 0 && leftDistance < parseInt(currentLeft)){
carouselImage[0].style.left = parseInt(currentLeft) + speed + "px";
setTimeout(go,10);
}else if(leftDistance < -1500){
carouselImage[0].style.left = -500 + "px";
}else if(leftDistance > -500){
carouselImage[0].style.left = -1500 + "px";
}
}
go(newoffset);
}
效果图
微信公众号:天字一等
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。