选中复选框时隐藏div而不使用JavaScript

时间:2017-08-19 04:44:50

标签: html css

除了隐藏div的实际功能之外的所有东西都在工作。我没有JavaScript需要这个的原因是因为它是一个没有JavaScript警告,可以被隐藏。我正在使用CSS尝试将div的显示设置为none,但我似乎没有做对。

HTML

<noscript>
    <div class="jswarning">
        JavaScript is disabled. For the best experience, enable it.
        <label class="jswarningbutton" for="hidejswarning">Hide</label>
        <input id="hidejswarning" type="checkbox">
    </div>
</noscript>

CSS

.jswarning {
    box-sizing: border-box;
    padding: 5px;
    background:red;
    width:100%;
    color:white;
    text-align:center;
}

.jswarningbutton {
    background: white;
    color: red;
    cursor: pointer;
}

.jswarningbutton + input {
    display: none;
}

.jswarningbutton + input[type=checkbox]:checked ~ .jswarning {
    display: none;
}

4 个答案:

答案 0 :(得分:2)

~CSS选择器称为General Sibling Selector。它选择前一个选择器的兄弟姐妹。

&#13;
&#13;
.jswarning {
box-sizing: border-box;
padding: 5px;
background:red;
width:100%;
color:white;
text-align:center;
}

.jswarningbutton {
background: white;
color: red;
cursor: pointer;
}

.jswarningbutton + input {
display: none;
}

.jswarningbutton + input[type=checkbox]:checked ~ .jswarning{
display: none;
}
&#13;
<label class="jswarningbutton" for="hidejswarning">Hide</label>
<input id="hidejswarning" type="checkbox">
<div class="jswarning">
    JavaScript is disabled. For the best experience, enable it.
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您错误地使用了~ CSS选择器。

~选择器应该用作p ~ ul。这意味着对每个ul标记前面的p应用此CSS。您可以在here中找到选择器参考。

答案 2 :(得分:0)

据报道,使用CSS无法实现这一点(截至2017年8月),我已成功使用PHP cookie。如果有人有兴趣,这是我使用的代码(可能有更好的方法):

主页(index.php)

<?php
    if(!isset($_COOKIE['hidejswarning'])){
        setcookie('hidejswarning', '0', time()+3600, '/');
        header('Location: index.php');
    }
?>

<!DOCTYPE html>
<html>
    <body>
        <?php
            if ($_COOKIE["hidejswarning"] != '1') {
                echo "
        <noscript>
            <div class='jswarning'>
                JavaScript is disabled. For the best experience, enable it. <a href='hidejswarning.php'>Hide</a>
            </div>
        </noscript>
                ";
            }
        ?>
    </body>
</html>

设置Cookie的页面(hidejswarning.php)

<?php
    setcookie('hidejswarning', '1', time()+3600, '/');
    header('Location: index.php');
?>
<html><body>Please wait...</body></html>

答案 3 :(得分:0)

1)你隐藏的东西需要是输入的兄弟,而不是父母。没有父选择器。轻松修复。

2)它需要在html中的输入标记之后。没有先前的兄弟选择器。难以修复您的外观。你需要一些凌乱的定位来获得一条消息,该消息在html中的复选框之后出现在它之前。

3)但是这种交互不需要在视觉上成为一个复选框。隐藏复选框输入标记(显示:无),单击标签仍然切换复选框状态。在输入标记之后,将消息放在标签内的div / span中。现在您可以使用〜选择器隐藏消息。也许用“hide”这个词来设计它,看起来很像。