html - 仅使用 CSS 选择选中的单选按钮的嵌套元素

标签 html css css-selectors

我正在尝试使用 CSS 根据 radio 选择一些元素按钮状态。

我想做的是如果某个 radio按钮被选中我想下降几个级别和unhide一个覆盖层,以便用户可以与残疾人互动 radio按钮。

我知道您可以使用类似 ~ 的同级选择器和 >选择当前 div 的 sibling ,但我如何选择 checked 的父元素?单选按钮,然后向下遍历 DOM 以找到我想要的选择器?

我可以用 JS 轻松做到这一点,但如果可能的话,我更喜欢 CSS。

这是一个CodePen

你可以看到我有四个 radio纽扣。其中两个略微缩进。

我想要完成的是,如果有人选择 Testing2 radio我想要 .overlay包含 opacity设置为 display: none .

我还需要在不重新组织 HTML 的情况下保持相同的结构。

使用兄弟选择器对我来说比较陌生,所以在这种情况下我可能没有正确使用它们。

我试过:

 #radio-1:checked ~ .overlay {
      display: none;
    }

    #radio-1:checked > .radio-bump > .radio-group-2 ~ .overlay {
      display: none;
    }

这是我的代码:

.overlay {
  background: #fff;
  z-index: 1;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  opacity: 0.7;
}
.radio-group-2 {
  position: relative;
}
.radio-bump {
  margin-left: 20px;
}
#radio-1:checked ~ .overlay {
  display: none;
}
#radio-1:checked > .radio-bump > .radio-group-2 ~ .overlay {
  display: none;
}
<div class="main-container">
  <div class="shipping-container">
    <div class="radio">
      <input type="radio" id="radio" name="radio-group-1">
      <label for="radio">Testing1</label>
    </div>
    <div class="radio-1">
      <input type="radio" id="radio-1" name="radio-group-1">
      <label for="radio-1">Testing2</label>
    </div>
    <div class="radio-bump">
      <div class="radio-group-2">
        <div class="overlay"></div>
        <div class="radios">
          <input type="radio" id="radio-2" name="radio-group-2">
          <label for="radio-2">Testing3</label>
        </div>
        <div class="radios">
          <input type="radio" id="radio-3" name="radio-group-2">
          <label for="radio-3">Testing4</label>
        </div>
      </div>
    </div>
  </div>
</div>

最佳答案

这只有在您从每个单选/标签中移除容器时才有可能(使用纯 CSS)。此外,您应该考虑使用指针事件而不是覆盖:

label:after { content: ""; display: block;}

.radio-group-2 {
  margin-left: 20px;
  opacity: .7;
  pointer-events: none;
}

input:checked + label + .radio-group-2 {
  opacity: 1;
  pointer-events: all;
}
<input type="radio" id="r-1" name="radio-group-1"><label for="r-1">Testing 1</label>
<input type="radio" id="r-2" name="radio-group-1"><label for="r-2">Testing 2</label>
<div class="radio-group-2">
  <input type="radio" id="r-3" name="radio-group-2"><label for="r-3">Testing 3</label>
  <input type="radio" id="r-4" name="radio-group-2"><label for="r-4">Testing 4</label>
</div>

注意相邻兄弟选择器的使用。

关于html - 仅使用 CSS 选择选中的单选按钮的嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37601647/

相关文章:

javascript - 单击按钮后显示 Google 翻译小部件

html - 一种更好的分隔导航栏元素的方法

html - 使用 WP 菜单链接到页面上的部分

html - 使用CSS检测child是否存在

css -/deep/OR::ng-deep 的长期替代方案是什么?

javascript - 如何实现jQuery的.not()?

jquery - 如何使表格行逐行动画

javascript - JQuery 查找和更改具有数据属性的所有元素的类

html - 工作导航但切换不打开

jquery - css 过渡效果在点击时不起作用?