簡體   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