简体   繁体   English

为什么通用同级组合器不能一直工作?

[英]Why is General sibling combinator not always working?

I have four divs, and i want to change their width and height on hover so the one you are hovering over expands and all others shrink for how much hovered one expanded. 我有四个div,我想在悬停时更改其宽度和高度,因此您要悬停的那一个会展开,而所有其他都会缩小,其中一个悬停了多少。 I managed to get it working when i hover over first div, but when i try to do the same with other three nothing happens. 当我将鼠标悬停在第一个div上时,我设法使其正常工作,但是当我尝试与其他三个div进行相同操作时,没有任何反应。 My HTML: 我的HTML:

<div  id="main">
        <div  id="mainOne">
            <h3>text</h3>
        </div>
        <div  id="mainTwo">
            <h3>text2</h3>
        </div>
        <div  id="mainThree">
            <h3>text3</h3>
        </div>
        <div  id="mainFour">
            <h3>text4</h3>
        </div>
    </div>

My CSS: 我的CSS:

/* HOVER 1 */

#mainOne:hover{
width:748px;
height:600px;
}

#mainOne:hover + #mainTwo{
width:248px;
height: 600px;
}

#mainOne:hover ~ #mainThree{
height:200px;
}
#mainOne:hover ~ #mainFour{
height:200px;
}

/* END HOVER 1 */

/* HOVER 2 */
#mainTwo:hover{
width:748px;
height:600px;
}

#mainTwo:hover + #mainOne{
width:248px;
height: 600px;
}
#mainTwo:hover + #mainThree{
height:200px;
}
#mainTwo:hover ~ #mainFour{
height:200px;
}

/* END HOVER 2 */

So when i hover over mainOne, everything changes, but when i hover over mainTwo just mainTwo changes and messes up everything else. 因此,当我将鼠标悬停在mainOne上时,所有内容都会发生变化,但是当我将鼠标悬停在mainTwo上时,仅mainTwo发生变化并弄乱了其他所有内容。 What am i doing wrong? 我究竟做错了什么? Thanks. 谢谢。

CSS can only ( currently ) target elements that appear later in the DOM, therefore #mainTwo + #mainThree will work, but #mainTwo + #mainOne cannot. CSS仅( 当前 )可以在DOM中稍后出现的目标元素,因此#mainTwo + #mainThree将起作用,但#mainTwo + #mainOne无法。

To target previous siblings you'd have to wrap the siblings within another, parent, element and then style the previous siblings based on the hover of that parent. 要定位先前的兄弟姐妹,您必须将兄弟姐妹包装在另一个父元素中,然后根据该父对象的悬停样式设置先前的兄弟姐妹的样式。

div > div {
    border: 1px solid #000;
    padding: 0.5em 1em;
    width: 80%;
    margin: 0 auto;
    color: #f00;
}

#main:hover > div {
    width: 50%;
}

#main:hover > div:hover ~ div {
    width: 50%;
}

#main:hover > div:hover {
    width: 80%;
}

JS fiddle proof-of-concept JS提琴概念证明

All your mainTwo rules with :hover use the adjacent sibling combinator. 您所有带有:hover mainTwo规则都使用相邻的同级组合器。

Only #mainTwo + #mainThree can match as neither #mainOne or #mainFour are the next sibling to #mainTwo . 只有#mainTwo + #mainThree可以匹配既不#mainOne#mainFour是下一个兄弟到#mainTwo

If you used the general sibling combinator ( ~ ) then you could match #mainFour too. 如果您使用了通用的同级组合器( ~ ),那么您也可以匹配#mainFour

Since #mainOne precedes #mainTwo , you can't match it with a rule that depends on the existence of #mainTwo . 由于#mainOne #mainTwo ,你不能依赖于是否存在规则匹配它#mainTwo

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

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