看题主的代码,我理解为:题主想做一个通过点击按钮轮番切换 div 的功能。以下为实现代码,纯 js DOM 操作,没有使用 JQuery
Documentdiv {
height: 100px;
width: 100px;
float: left;
display: none;
}
div:nth-child(1) {
background-color:chocolate;
}
div:nth-child(2) {
background-color:darkgoldenrod;
}
div:nth-child(3) {
background-color:darkmagenta;
}
.active {
display: block;
}
上一页
下一页
function next() {
let divEl = document.getElementsByClassName('active')[0],
nextEl = divEl.nextElementSibling;
divEl.className = '';
if (nextEl) {
nextEl.className = 'active';
} else {
document.getElementById('box').firstElementChild.className = 'active';
}
}
function pre() {
let divEl = document.getElementsByClassName('active')[0],
preEl = divEl.previousElementSibling;
divEl.className = '';
if (preEl) {
preEl.className = 'active';
} else {
document.getElementById('box').lastElementChild.className = 'active';
}
}