还添加了注释以供您参考已实现的逻辑
在此处检查更新的小提琴
$(document).ready(function() {
var img = [];
// Create images array to be looped through
img[0] = '<img src="Hydrangeas.jpg" id ="image" class="image" alt=""/>';
img[1] = '<img src="Jellyfish.jpg" id="image-two" class="image" alt=""/>';
img[2] = '<img src="Koala.jpg" id="image-three" class="image" alt=""/>';
// Counter for looping through img array
var i = 0;
var stage = $(".gallery");
stage.append(img[i]);
var secondimage = null;
var firstimage = $("img:eq(0)");
firstimage.css('margin-left', -firstimage.width());
function gallery() {
// Since we need to show to images at a certain point of time and to move both the images i have used, firstimage and secondimage
if (firstimage !== null) {
// If firstimage is set animate that
firstimage.animate({"margin-left": "+=100px"}, {duration: 1000, easing: "linear", progress: checkBox});
}
if (secondimage !== null) {
// If secondimage is set animate that
secondimage.animate({"margin-left": "+=100px"}, {duration: 1000, easing: "linear", progress: checkBox});
}
}
var interv = setInterval(gallery, 1000);
function checkBox() {
// If first image is not null and second is null and first image is about to move out of div,
// set second image as another iteration of img variable, once it moves out it is set as null
// If second image is not null and first is null and second image is about to move out of div,
// set first image as another iteration of img variable, once it moves out it is set as null
// Finally, if all the iterations are set, then set i as -1 i.e. reset counter
if ((secondimage === null && firstimage !== null && parseInt(firstimage.css('margin-left')) > parseInt(stage.width() / 3))
|| (firstimage === null && secondimage !== null && parseInt(secondimage.css('margin-left')) > parseInt(stage.width() / 3)) || (i === -1)) {
i += 1;
if (i < img.length) {
stage.prepend(img[i]);
$("img:eq(0)").css('margin-left', -$("img:eq(0)").width());
if (secondimage === null) {
secondimage = $("img:eq(0)");
} else {
firstimage = $("img:eq(0)");
}
} else {
i = -1;
}
} else if (firstimage !== null && (parseInt(firstimage.css('margin-left')) > parseInt(stage.width()))) {
// remove first image
firstimage.remove();
firstimage = null;
} else if (secondimage !== null && (parseInt(secondimage.css('margin-left')) > parseInt(stage.width()))) {
// remove second image
secondimage.remove();
secondimage = null;
}
}
});