时间:2019-04-29 16:41:59

标签: html css checkbox

当我将复选框嵌套在<div>元素中时,我的代码停止工作。选中某个复选框后,我需要显示图像。代码工作时不会在<div>中嵌套复选框。

我希望我的复选框嵌套在<div>中,以便在选中某个复选框后,将<div>中的图像的显示值从无更改为行内块。

我已经尝试了一切,但我想我无法解决这个问题。

<body>

<style>
  input[type=checkbox]:checked.ivo ~ div #fotoivo {
    display: inline-block;
 }

input[type=checkbox]:checked.ian ~ div #fotoian {
    display: inline-block;
 }

input[type=checkbox]:checked.non ~ div #fotonon {
    display: inline-block;
 }

#fotoivo {
    width: 200px;
    display: none;
}

#fotoian {
    width: 200px;
    display: none;
}

#fotonon {
    width: 200px;
    display: none;
}
</style>

<!--Checkboxes (works without the <div> wrapped around)-->
<!--<div>-->
  Ivo: <input type="checkbox" name="ivoian" class="ivo">
  Ian: <input type="checkbox" name="ivoian" class="ian">
  Non-binair: <input type="checkbox" name="ivoian" class="non">
<!--</div>-->

<!--Images that should change from display: none to inline-block.-->
  <div>
    <img id="fotoivo" src="ivo.jpg" alt="#">

    <img id="fotoian" src="ian.jpg" alt="#">

    <img id="fotonon" src="non.jpg" alt="#">
  </div>

</body>

1 个答案:

答案 0 :(得分:0)

Tilda(~)是同级选择器。当您嵌套输入时,div包装的图像不再是它们的兄弟。由于CSS没有父选择器,因此无法仅使用CSS来完成。但是,当然,您可以使用简单的JS来做到这一点。

您可以执行以下操作:https://stackoverflow.com/a/7691692/11404579

编辑:而且,仅CSS几乎没有什么骇人听闻的方法,但是您将失去本机输入。您可以将输入放置在根元素中,以便可以使用同级选择器选择图像并隐藏输入。并在某些嵌套元素中为这些隐藏的输入放置标签。这样,当您单击(嵌套)标签时,便检查了可以控制内容的输入。