我的 css 知识在这里有差距。当另一个元素悬停在使用 styled-components 上时,我试图隐藏一个元素。
const InnerBox = styled.div`
background: green;
height: 20px;
width: 20px;
margin: 0 auto;
`
const BoxTwo = styled.div`
height: 40px;
width: 40px;
background: red;
`
const Box = styled.div`
height: 40px;
width: 40px;
background: pink;
// This works as InnerBox is in Box
&:hover ${InnerBox} {
display: none;
}
// This doesn't work as BoxTwo is not in Box
&:hover ${BoxTwo} {
display: none;
}
`
我的 jsx 看起来像这样:
<BoxTwo />
<Box>
<InnerBox />
</Box>
<BoxTwo />
有谁知道如何通过悬停在 Box 上来定位两个 BoxTwo?
好像不是possible .我可以定位后一个,但不能定位前一个
最佳答案
您可以使用 +
选择器:
#innerBox {
background: green;
height: 20px;
width: 20px;
margin: 0 auto;
}
#boxTwo {
height: 40px;
width: 40px;
background: red;
}
#box {
height: 40px;
width: 40px;
background: pink;
}
#box:hover #innerBox,
#box:hover + #boxTwo {
display: none;
}
<div id="box">
<div id="innerBox"></div>
</div>
<div id="boxTwo"></div>
在你的情况下它将是:
&:hover + ${BoxTwo} {
display: none;
}
只有当元素 (BoxTwo
) 紧跟在父选择器 (Box
) 之后时,+
选择器才会起作用。
关于javascript - 在悬停 css 上隐藏一个不是直接子元素的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54536256/