2 回答
TA贡献1796条经验 获得超4个赞
您可以简单地为所有日期创建一个选择器,循环它们,然后在到达 时开始添加类,.day-start并在到达 时停止添加.day-end。
就像是:
var active = false;
document.querySelectorAll('.day').forEach((day) => {
if(day.classList.contains("day-start")) {
active = true;
}
if(active) {
day.classList.add("foo");
}
if(day.classList.contains("day-end")) {
active = false;
}
});
我在这里为您创建了一个示例:https://codepen.io/bj-rn-nyborg/pen/OJRJwEN
TA贡献1797条经验 获得超6个赞
您需要跟踪之间的元素。像这样的东西:
let section = 0; // our flag: 0 - before, 1 - in-between, 2 - after
document.querySelectorAll('.day').forEach(
el => {
if (section === 0 && el.classList.contains('day-start')) {
section = 1;
} else if (section === 1 && el.classList.contains('day-end')) {
section = 2;
// now, if this was a loop, we could simply `break;` it
// but `forEach` doesn't offer that
}
if (section === 1) { // we apply this logic only for divs in section 1
el.querySelectorAll('div').forEach(
div => div.style.color = 'red'
)
}
}
);
使用循环,会更简单一些:
let isBefore = true;
for (const el of document.querySelectorAll('.day')) {
if (isBefore && el.classList.contains('day-start')) {
isBefore = false;
} else if (el.classList.contains('day-end')) {
break; // we're ending all iteration here
}
if (isBefore) continue; // we finish the current round here, and go to another `el`
el.querySelectorAll('div').forEach(
div => div.style.color = 'red'
);
}
添加回答
举报