我正在构建轮播,但似乎无法弄清楚如何用下一张和上一张替换当前的图像。我已经附加了一个Codepen和我要实现的屏幕截图。
Codepen: https://codepen.io/anon/pen/bmQjRB
JS:
const img_con = document.getElementById('img-con');
const img_con1 = document.getElementById('img-con-1');
const img_con2 = document.getElementById('img-con-2');
const next = document.getElementById('next');
const prev = document.getElementById('prev');
const images = ['https://images.unsplash.com/photo-1506126483163-f4d1558dbf85?ixlib=rb-0.3.5&q=85&fm=jpg', 'https://images.unsplash.com/photo-1506252374453-ef5237291d83?ixlib=rb-0.3.5&q=85&fm=jpg', 'https://images.unsplash.com/photo-1525183995014-bd94c0750cd5?ixlib=rb-0.3.5&q=85&fm=jpg']
let i = images.length;
next.onclick = ()=> {
i = (i<images.length) ? (i= i+1) : (i=1);
img_con.innerHTML = "<img class='img' src="+images[i-1]+">";
}
prev.onclick = ()=> {
i = (i<images.length+1 && i>1) ?(i= i-1):(i=images.length);
img_con.innerHTML = "<img class='img' src="+images[i-1]+">";
}
答案 0 :(得分:2)
我将images数组更改为具有适当顺序的图像。
const images = ['https://images.unsplash.com/photo-1525183995014-bd94c0750cd5?ixlib=rb-0.3.5&q=85&fm=jpg',
'https://images.unsplash.com/photo-1506126483163-f4d1558dbf85?ixlib=rb-0.3.5&q=85&fm=jpg',
'https://images.unsplash.com/photo-1506252374453-ef5237291d83?ixlib=rb-0.3.5&q=85&fm=jpg'
]
此外,您需要运行for循环以检查索引。我将为下一次按钮附加完整的工作代码。
let i =0;
next.onclick = () => {
let temp = images[0];
for (let index = 0; index < images.length; index++) {
images[index] = images[index + 1];
if (index === images.length-1 ) {
images[index] = temp;
}
}
img_con1.innerHTML = "<img class='img' src=" + images[i] + ">";
img_con.innerHTML = "<img class='img' src=" + images[i + 1] + ">";
img_con2.innerHTML = "<img class='img' src=" + images[i + 2] + ">";
}
对于预按钮yu,您需要运行循环反向词
let j = 0;
prev.onclick = () => {
let temp = images[images.length-1];
for (let index = images.length-1; index >=0; index--) {
images[index] = images[index - 1];
if (index === 0 ) {
console.log(index);
images[index] = temp;
}
}
img_con1.innerHTML = "<img class='img' src=" + images[j] + ">";
img_con.innerHTML = "<img class='img' src=" + images[j + 1] + ">";
img_con2.innerHTML = "<img class='img' src=" + images[j + 2] + ">";
}