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'
);
}
添加回答
舉報