亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我如何將樣式從一個類應用到另一個類,以及其間的所有項目

我如何將樣式從一個類應用到另一個類,以及其間的所有項目

PIPIONE 2023-09-14 22:07:06
我想在“day-start”和“day-end”之間的所有子元素上添加特定的樣式屬性我嘗試過使用這樣的代碼:document.querySelectorAll('.day').forEach(el => el.querySelectorAll('div').forEach(el => el.style.color = 'red'));但不確定如何在這兩個類之間添加它使用 jQuery 解決方案: $(".day-start").nextUntil(".day-end").addClass("foo");將類添加到正確的元素,但在表行標記上中斷+它不包含 .day-start + .day-end 類是否可以將類添加到所有添加了背景顏色的內容中?作為替代解決方案?
查看完整描述

2 回答

?
SMILET

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


查看完整回答
反對 回復 2023-09-14
?
FFIVE

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'

    );

 }


查看完整回答
反對 回復 2023-09-14
  • 2 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號