html - 带有复选框的目标 div

标签 html css checkbox

我有一个复选框可以隐藏/显示一个 div。当我将复选框直接放在 div 上方时,它会起作用。当我将复选框放在页面的其他位置(为了更好的可用性)时,它不起作用。有没有一种方法可以定位某个 div,使复选框在页面的任何位置都有效?

这是 HTML 代码:

<input type="checkbox" id="toggle-result" checked="checked">  </input>

CSS:

input[type=checkbox]:checked ~ div {
   display: none;
}

最佳答案

使用 CSS,您可以选择子元素和相邻元素,因此如果 div 紧跟在复选框之后,您尝试执行的操作将起作用,但如果您想让它在 div在别的地方(checkbox上面),需要用JavaScript,如果在后面,可以用+选择相邻元素或嵌套相邻元素

Demo

<input type="checkbox" />
<div>Toggle Using CSS</div>

input[type=checkbox]:checked + div {
    display: block;
}

div {
    display: none;
}

目标 div 像这样远离某个地方(但不在 checkbox 之前)

Demo 2

input[type=checkbox]:checked + a + .blah .target {
    display: block;
}

.target {
    display: none;
}

<input type="checkbox" />
<a href="#">Dummy Link</a>

<div class="blah">
    <div class="target">Complicated Selector, Isn't It?</div>
</div>

Explanation : input[type=checkbox]:checked + a + .blah .target Over here we select the checkbox which is in a checked state, and than we chain this by selecting the adjacent element which is an anchor tag, and than we select another adjacent element which is adjacent to a tag which is div with a class .blah, and than we select nested child element with a class .target

使用 jQuery To Do(无论目标元素在哪里)Demo 3

<input type="checkbox" id="checkme" />
<a href="#">Dummy Link</a>
<div id="show_on_check" style="display:none">
    This content should appear when the checkbox is checked
</div>

$(document).ready(function() {
    $('#checkme').change(function() {
        $('#show_on_check').toggle();
    });
});

关于html - 带有复选框的目标 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16694125/

相关文章:

html - 如何让这个带有溢出自动的子元素在父元素溢出隐藏时显示?

jQuery SimpleModal 显示滚动条

android - CompoundButton Checkbox 在哪里/如何测量可绘制复选框的宽度

javascript - div 中的 Jquery 复选框

checkbox - DevExpress XtraGrid 复选框检查未注册,除非焦点更改

angularjs - Laravel 5 + AngularJS html5Mode

javascript - 在 JavaScript 创建的输入中获取反斜杠

html - 带背景的 Bootstrap 列之间的间距

html - IE 7 调试问题 - 神秘的 <li> 第一行缩进

css - 错误 : Task not found: "prefix.css", compress.css“在 npm 构建之后:css 命令