这个JS可以用纯CSS编写吗?

时间:2022-11-05 11:47:50
jQuery('.parent:visible').each(function () {
  if (jQuery(this).find('.child-1').is(':hidden')) {
    jQuery(this).find('.child-2').css('color', '#000')
  }
});

Selecting the children are easy, separately, but since there are no if statements in CSS, I'm hoping there's some magic CSS I'm missing.

选择孩子很容易,分开,但由于CSS中没有if语句,我希望有一些我缺少的神奇CSS。

edit: fixing js as per suggestions

编辑:根据建议修复js

2 个解决方案

#1


7  

.parent:not(.hidden) .child-1:not(.hidden) + .child-2 perhaps?

.parent:not(.hidden).child-1:不是(.hidden)+ .child-2也许?


Demo

.parent { border:1px solid red; }
.hidden { display:none; }

.parent:not(.hidden) .child-1:not(.hidden) + .child-2 {
    color:green;
}
<div class="parent">
    <div class="child-1">one</div>
    <div class="child-2">two</div>
</div>

<div class="parent">
    <div class="child-1 hidden">one</div>
    <div class="child-2">two</div>
</div>

<div class="parent hidden">
    <div class="child-1">one</div>
    <div class="child-2">two</div>
</div>

<div class="parent">
    <div class="child-1">one</div>
    <div class="child-2">two</div>
</div>

#2


0  

If you can add classes to the elements based on their visibility, then you can do this.

如果您可以根据元素的可见性向元素添加类,则可以执行此操作。

.parent.visible .child-1.not-visible + .child-2 {
    color: #000
}

This will check if a .child-1 inside a .parent.visible has a class of .not-visible -- if it does, then the adjacent sibling with a class .child-2 will inherit this rule.

这将检查.parent.visible中的.child-1是否具有.not-visible类 - 如果确实如此,那么具有类.child-2的相邻兄弟将继承此规则。

Otherwise, you have to use JavaScript as CSS doesn't have a way to test if an element is visible or not.

否则,您必须使用JavaScript,因为CSS没有办法测试元素是否可见。

#1


7  

.parent:not(.hidden) .child-1:not(.hidden) + .child-2 perhaps?

.parent:not(.hidden).child-1:不是(.hidden)+ .child-2也许?


Demo

.parent { border:1px solid red; }
.hidden { display:none; }

.parent:not(.hidden) .child-1:not(.hidden) + .child-2 {
    color:green;
}
<div class="parent">
    <div class="child-1">one</div>
    <div class="child-2">two</div>
</div>

<div class="parent">
    <div class="child-1 hidden">one</div>
    <div class="child-2">two</div>
</div>

<div class="parent hidden">
    <div class="child-1">one</div>
    <div class="child-2">two</div>
</div>

<div class="parent">
    <div class="child-1">one</div>
    <div class="child-2">two</div>
</div>

#2


0  

If you can add classes to the elements based on their visibility, then you can do this.

如果您可以根据元素的可见性向元素添加类,则可以执行此操作。

.parent.visible .child-1.not-visible + .child-2 {
    color: #000
}

This will check if a .child-1 inside a .parent.visible has a class of .not-visible -- if it does, then the adjacent sibling with a class .child-2 will inherit this rule.

这将检查.parent.visible中的.child-1是否具有.not-visible类 - 如果确实如此,那么具有类.child-2的相邻兄弟将继承此规则。

Otherwise, you have to use JavaScript as CSS doesn't have a way to test if an element is visible or not.

否则,您必须使用JavaScript,因为CSS没有办法测试元素是否可见。