1 效果
2 代码
// 作业1: 为每个翻页按钮添加事件完成图片翻页(兄弟节点的处理)
skip.firstElementChild.addEventListener("click", skip_prev, false); //向前翻页
skip.lastElementChild.addEventListener("click", skip_next, false); //向后翻页
function skip_prev() {
let now_index = getActiveImg(imgs).dataset.index;
let img_number = imgs.length;
let prev_index = now_index * 1 - 1 === 0 ? img_number : now_index * 1 - 1;
console.log(now_index, prev_index);
setActive(now_index, prev_index);
}
function skip_next() {
let now_index = getActiveImg(imgs).dataset.index;
let img_number = imgs.length;
let next_index = now_index * 1 + 1 === img_number * 1 + 1 ? 1 : now_index * 1 + 1;
console.log(now_index, next_index);
setActive(now_index, next_index);
}
function setActive(remove_index, active_index) {
//激活并取消激活
imgs.forEach((img) => {
if (img.dataset.index == active_index) {
img.classList.add("active");
}
if (img.dataset.index == remove_index) {
img.classList.remove("active");
}
});
Array.from(btns.children).forEach((btn) => {
if (btn.dataset.index == active_index) {
btn.classList.add("active");
}
if (btn.dataset.index == remove_index) {
btn.classList.remove("active");
}
});
}
// 作业2: 图片每隔2秒自动播放(定时器,事件自动派发)
setInterval(() => {
skip_next();
}, 2000);
3 总结
感谢老师教导!
兄弟节点网上找了不能用,就用索引来实现了,jQuery看着很容易实现。