首页 > 解决方案 > 是否有一个 CSS 选择器可以用来在选中复选框后显示元素,无论它在页面上的什么位置?

问题描述

使用~css 选择器,可以在单击复选框后显示一些元素,一旦单击元素,可以使用它来显示和隐藏菜单,如本教程所示

但是波浪号选择器不会选择页面上的所有元素,是否有选择器可以选择?

我希望在单击复选框后显示或隐藏.showtextand标记。这是一个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;
}

标签: htmlcsscheckboxcss-selectors

解决方案


我认为复选框的问题在于这些跨度位于您正在检查的复选框的标签内。: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>


推荐阅读