繁体   English   中英

纯CSS,div悬停会影响多个元素

[英]Pure CSS, div hover can affect more than one element

像本示例一样,当将鼠标悬停在另一个div元素上时,可以更改div元素的大小。 https://jsfiddle.net/9510a6kj/

 .left, .right{
        float:left;
    }

    .left{
        background: red;
        width: 200px;
        height: 300px;
        transition: width 1s ;
    }

    .right{
        background: blue;
        width: 300px;
        height: 300px;
        transition: width 1s;
    }

    .left:hover{
        width: 300px;
    }

    .left:hover + .right{
        width: 100px;
    }
    </style>

但是当悬停在第一个元素上时,可以更改两个不同的div元素的大小。

例如,将鼠标悬停在div“ a”上,更改div“ b”和div“ c”的大小。

谢谢。

是的,您可以使用同级选择器进行操作。 虽然您在小提琴中使用的相邻兄弟选择器将在DOM中紧随其后的元素设置样式,但兄弟选择器将对所有跟随 .a的兄弟元素进行样式设置。

HTML

<div class="parent">
   <div class="a"></div>
   <div class="b"></div>
   <div class="c"></div>
</div>

CSS

.a:hover ~ div{
 //style .b and .c here
}

不过请注意,同级选择器仅适用于后面的同级 ...对引用元素之前的同级不起作用。 CSS尚不能备份DOM树。

是,使用同级选择器(如果它们是同级)

 .a { display: inline-block; width: 100px; height: 50px; background-color: red; } .b { display: inline-block; width: 100px; height: 30px; background-color: blue; transition: all 1s; } .c { display: inline-block; width: 100px; height: 80px; background-color: yellow; transition: all 1s; } .a:hover~.b { height: 160px; } .a:hover~.c { height: 120px; } 
 <div class="a">hover me</div> <div class="b">bbbb b</div> <div class="c">cccc c</div> 

这完全取决于这些元素之间的关系。

1.如果它们是兄弟姐妹,一个接一个,则对c div也使用+ 见下文

 div { height: 50px; width: 50px; border: 1px solid black } .a:hover + .b { background: blue; } .a:hover + .b + .c { background: red; } 
 <div class="a"> a </div> <div class="b"> b </div> <div class="c"> c </div> 

2.如果它们是兄弟姐妹,并且bc a 后面 ,但不是一个接一个,则使用~

 div { height: 50px; width: 50px; border: 1px solid black } .a:hover ~ .b { background: blue; } .a:hover ~ .c { background: red; } 
 <div class="a"> a </div> <div> </div> <div class="b"> b </div> <div> </div> <div class="c"> c </div> 

3.如果bc a之后,但不是紧接着在c之后,而cb之后,则可以将~+一起使用

 div { height: 50px; width: 50px; border: 1px solid black } .a:hover ~ .b { background: blue; } .a:hover ~ .b + .c { background: red; } 
 <div class="a"> a </div> <div> </div> <div class="b"> b </div> <div class="c"> c </div> 

  1. 如果它们是孩子,则可以使用a:hover b,a:hover c> (直接孩子),然后可以添加上述同级选择器。

正如我所说,有很多可能性。 一切都取决于结构。 你只能用CSS如果这样做bc跟从a DOM树。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM