【问题标题】:use 1 css class to swap style for children使用 1 个 css 类为孩子交换样式
【发布时间】:2013-10-25 20:40:16
【问题描述】:

我想在 div id="slot1" 上切换单个类 .active。

该 div 有 2 个子 div。当 .active 未应用于 div 时,一个 child1 为黄色,child2 为绿色。 当我申请 $("#slot").addClass("active") 之类的操作时,我希望 child1 为蓝色,child2 为红色。

如何为“孩子”编写 css,以便在其父“插槽”上切换 .active 使他们切换状态

.normal{}
.active{}
.a{color:yellow;}
.b{color:green;}

.a [when .active is applied to my daddy] {color:blue;}
.b [when .active is applied to my daddy] {color:red;}

<div id="slot1" class="normal">
  <div class="a">normal I'm yellow, with active I'm blue</div>
  <div class="b">normal I'm green, with active I'm red</div>
</div>

<div id="slot2" class="normal active">
  <div class="a">normal I'm yellow, with active I'm blue</div>
  <div class="b">normal I'm green, with active I'm red</div>
</div>

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    正常

    .normal .a {
        background: yellow;
    }
    

    主动

    .normal.active .a {
        background: blue;
    }
    

    对于其他的孩子,它是等价的,请参阅JSFiddle

    如果你只想选择直接祖先(爸爸),你必须使用子选择器&gt;

    .normal > .a {
        background: yellow;
    }
    
    .normal.active > .a {
        background: blue;
    }
    

    【讨论】:

    • 感谢您的提琴。原来我正在寻找 .normal.active a 并看到小提琴帮助我做对了。
    • .normal.active &gt; .a 效果更好,因为它更具体,因此不依赖于顺序,请参阅JSFiddle。我相应地更新了答案。
    【解决方案2】:
    .a{color:yellow;}
    .b{color:green;}
    
    #slot1.active .a, #slot2.active .a {color:blue;} /*No daddy selector, but you can just get the child of .active*/
    #slot1.active .b, #slot2.active .b {color:red;}
    

    【讨论】:

    • 好的,所以我要找的最终是 .normal.active a 但是谢谢,你让我走上了正轨
    猜你喜欢
    • 2016-11-30
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2013-08-19
    • 2020-11-03
    • 2013-09-02
    相关资源
    最近更新 更多