Document
inter

其实按正常思路来讲,这是前端最基础的一个功能,相当于京东,淘宝头部导航栏的一个小功能,其实这功能是可以通过js来写的,而且更灵活,但本文主要讲css,所以不做延伸

其实本文的重点是,如何控制其他元素的显示隐藏或样式修改,非子元素

例如,这样一段代码

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    </style>
</head>
    <div class="app">
    <div class="bottom">bottom</div>
</body>
</html>

如何通过app类显示隐藏bottom类

是的,我们可以用到相邻兄弟选择器

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .bottom {
            display: none;
        .app:hover+.bottom {
            display: block;
    </style>
</head>
    <div class="app">
    <div class="bottom">bottom</div>
</body>
</html>

这个时候有人就要问了,什么是相邻兄弟选择器?

相邻兄弟选择器(Adjacent sibling selector)可选择紧接在另一元素后的元素,且二者有相同父元素。

可能有些有心的看客表示,如果不是相邻的呢。

其实是有办法的,看代码

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .bottom {
            display: none;
        .app:hover~.bottom {
            display: block;
    </style>
</head>
    <div class="app">
    <div class="app_bottom">app_bottom</div>
    <div class="bottom">bottom</div>
</body>
</html>

这里用到了兄弟选择器

兄弟选择器:~表示某元素后所有同级的指定元素,强调所有的

可能有人又会问了,如果上面的代码里有两个bottom,但是我只想显示一个bottom里的内容怎么办?

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .bottom {
            display: none;
        .app:hover~.bottom.show {
            display: block;
    </style>
</head>
    <div class="app">
    <div class="app_bottom">app_bottom</div>
    <div class="bottom">bottom</div>
    <div class="bottom show">bottom bottom</div>
</body>
</html>

不能跟电脑死干,做一些无法改变的事,我们灵活一点,修改兄弟选择器的指向。

可能有些聪明人会问,那我能不能显示多个元素

如果使用兄弟选择器绝对ok

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .bottom {
            display: none;
        .app:hover~.bottom.show {
            display: block;
    </style>
</head>
    <div class="app">
    <div class="app_bottom">app_bottom</div>
    <div class="bottom">bottom</div>
    <div class="bottom show">bottom bottom</div>
    <div class="bottom show">bottom bottom</div>
</body>
</html>

这样不就实现了吗?O(∩_∩)O

本文内容已结束