我正在尝试创建一个无限幻灯片,并尝试了无数次尝试通过移动容器使其无限。您可以看到过渡正常,但是问题是当您到达终点时,您可以看到它又回到了起点。谁能建议如何创造无限效果?
JS fiddle here(如果人们喜欢),否则请参见以下代码:
$(document).ready(function() {
const numSlides = 6;
let index = 0;
$('.next-arrow').click(function() {
const slideWidth = $('.card').outerWidth(true);
index += 1;
if (index === numSlides) {
index = 0;
}
$('.card').css('transform', `translateX(-${slideWidth * index}px)`)
});
$('.prev-arrow').click(function() {
const slideWidth = $('.card').outerWidth(true);
index -= 1;
if (index < 0) {
index = numSlides - 1;
}
$('.card').css('transform', `translateX(-${slideWidth * index}px)`);
});
});
.slideshow-wrapper {
width: 250px;
display: flex;
justify-content: space-between;
flex-wrap: nowrap;
flex-direction: row;
}
.card {
flex: 1 0 100%;
margin: 0 5px;
height: 100px;
width: 300px;
transition: transform 0.5s;
}
.one {
background: red;
}
.two {
background: blue;
}
.three {
background: yellow;
}
.four {
background: orange;
}
.five {
background: pink;
}
.six {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='slideshow-wrapper'>
<div class="card one"></div>
<div class="card two"></div>
<div class="card three"></div>
<div class="card four"></div>
<div class="card five"></div>
<div class="card six"></div>
</div>
<button class="prev-arrow">PREV</button>
<button class="next-arrow">NEXT</button>
答案 0 :(得分:1)
我使用flexbox的order属性为“下一步”按钮创建了代码。我认为代码可以说明一切,但是我在其中添加了一些注释。
我确定您可以自己弄清楚“上一个”按钮的功能;)
$(document).ready(function() {
$('.next-arrow').click(function() {
const slideWidth = $('.card').outerWidth(true);
const anim = (slideWidth) * -1 + "px";
$('.slideshow-wrapper')
.animate({'marginLeft' : anim}, 500, function() {
/* When animation is ready, reorganize the order of elements */
$(".card").each( function(index, element) {
const currentOrder = $(element).css("order");
let newOrder = currentOrder - 1;
if (newOrder === 0) {
newOrder = 6;
/* When the first item is moved, reset the margin */
$('.slideshow-wrapper').css("margin-left", "0px");
}
$(element).css("order", newOrder);
});
});
});
$('.prev-arrow').click(function() {
const slideWidth = $('.card').outerWidth(true);
});
});
.slideshow-wrapper {
display: flex;
}
.card {
flex: 1 0 100%;
margin: 0 5px;
height: 100px;
max-width: 300px;
}
.one {
background: red;
order: 1;
}
.two {
background: blue;
order: 2;
}
.three {
background: yellow;
order: 3;
}
.four {
background: orange;
order: 4;
}
.five {
background: pink;
order: 5;
}
.six {
background: green;
order: 6;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='slideshow-wrapper'>
<div class="card one"></div>
<div class="card two"></div>
<div class="card three"></div>
<div class="card four"></div>
<div class="card five"></div>
<div class="card six"></div>
</div>
<button class="prev-arrow">PREV</button>
<button class="next-arrow">NEXT</button>