【问题标题】:How do i apply style from one class to another, to all items inbetween我如何将样式从一个类应用到另一个类,以及其间的所有项目
【发布时间】:2021-03-10 01:23:45
【问题描述】:

我想在“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 类

是否可以将类添加到添加了背景颜色的所有内容中?作为替代解决方案?

【问题讨论】:

  • 你可以只使用<div>'s 代替表格,然后display: grid; 然后你可以使用jQuery 函数。 ??????
  • @BjørnNyborg 有效点,但不幸的是我无法更改 HTML 结构:(

标签: javascript jquery css dom css-selectors


【解决方案1】:

您可以简单地为所有天创建一个选择器,循环它们,然后在到达 .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

【讨论】:

  • 非常好的解决方案,请注意;如果我只想将类添加到包含内联背景颜色样式的日期,无论样式是什么颜色,您会推荐什么解决方案?
  • 您可以使用element.style.backgroundColor !== '' 来检查元素是否具有背景色。 ?
【解决方案2】:

您需要在两者之间跟踪元素。类似的东西:

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-03-26
    • 2011-03-03
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    相关资源
    最近更新 更多