html - 是否有一个 CSS 选择器可以用来在选中复选框后显示元素,无论它在页面上的什么位置?
问题描述
使用~
css 选择器,可以在单击复选框后显示一些元素,一旦单击元素,可以使用它来显示和隐藏菜单,如本教程所示。
但是波浪号选择器不会选择页面上的所有元素,是否有选择器可以选择?
我希望在单击复选框后显示或隐藏.showtext
and标记。这是一个js小提琴链接。.hidetext
<span>
HTML
<!-- The checkbox input & label partner -->
<input type="checkbox" id="menu-toggle">
<label for="menu-toggle">Menu
<span class="showtext">show menu</span>
<span class="hidetext">hide menu</span>
</label>
<!-- The navigation we wish to toggle -->
<nav>
<ul>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Articles</a></li>
<li><a href="">Colophon</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
CSS
.hidetext { display: none }
input[type="checkbox"]:checked .hidetext{
display: block;
}
/* Set the input position to absolute, send it off screen with zero opacity */
input[type="checkbox"] {
left: -9999px;
opacity: 0;
position: absolute;
}
/* Minor visual styling to make the label more button-y */
label {
border: 1px solid currentColor;
border-radius: 4px;
cursor: pointer;
padding: 10px;
}
/* Set nav to absolute (avoids odd page rendering space pop-in) */
nav {
opacity: 0;
position: absolute;
z-index: -2;
}
/* Show nav when checkbox is checked */
input[type="checkbox"]:checked ~ nav {
opacity: 1;
z-index: 1;
}
解决方案
我认为复选框的问题在于这些跨度位于您正在检查的复选框的标签内。:after
这是一个纯 HTML/CSS 方法,它将使用psuedo 元素为您提供所需的结果label
,以显示和隐藏“显示菜单”和“隐藏菜单”文本。我希望这对你有用。
.hidetext { display: none }
input[type="checkbox"]:checked .hidetext{
display: block;
}
/* Set the input position to absolute, send it off screen with zero opacity */
input[type="checkbox"] {
left: -9999px;
opacity: 0;
position: absolute;
}
/* Minor visual styling to make the label more button-y */
label {
border: 1px solid currentColor;
border-radius: 4px;
cursor: pointer;
padding: 10px;
}
/* Set nav to absolute (avoids odd page rendering space pop-in) */
nav {
opacity: 0;
position: absolute;
z-index: -2;
}
/* Show nav when checkbox is checked */
input[type="checkbox"]:checked ~ nav {
opacity: 1;
z-index: 1;
}
label:after {
content: " show menu"
}
input[type="checkbox"]:checked ~ label:after {
content: " hide menu";
}
<!-- The checkbox input & label partner -->
<input type="checkbox" id="menu-toggle">
<label for="menu-toggle">Menu</label>
<!-- The navigation we wish to toggle -->
<nav>
<ul>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Articles</a></li>
<li><a href="">Colophon</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
推荐阅读
- javascript - 如何测试用多个高阶组件包装的组件?
- c# - WPF - 绑定获取属性
- elasticsearch - 使用 java API 进行 Elasticsearch 排序
- payment-gateway - PayUmoney 支付每次都失败
- java - 没有为类 org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 找到序列化程序,也没有发现创建 BeanSerializer 的属性
- php - Wordpress在functions.php中获取隐藏输入字段的值
- mysql - 巨大的 INSERT 列表的 ProgressBar - UPDATE 查询
- angular - 如何在材料设计 Angular 6 中设置时间选择器?
- java - Intellij Spring Boot 运行无法自动加载 application.yml
- c# - Identity Server 4 刷新令牌存储