我有一个 SVG 复选框,其中有一个 circle
元素围绕着一个 polyline
元素(复选标记)。因为图标边界超出了圆圈,所以在图标本身上使用 &:hover
意味着当悬停在圆圈边界之外时您会看到样式发生变化。所以我只想更改样式:将鼠标悬停在圆圈本身上。但我显然需要在悬停时同时更改圆和多段线。我正在使用样式组件。
我已经尝试了所有我能想到的方法来让多段线在圆圈悬停时发生变化。
我开始尝试类似的东西:
& circle:hover circle, & circle:hover polyline { }
以及一些变体。最终,我将圆和折线元素制作成样式组件,以便更容易地插入它们。基于this post我尝试了这个解决方案:
const Circle = styled.circle``;
const Polyline = styled.polyline``;
const Icon = styled.svg`
width: 52px;
height: 52px;
& ${Circle}, ${Polyline} {
fill: #fff;
stroke: ${props => props.logged ? colors.secondary200 : colors.secondary400};
& ${Circle}:hover {
stroke: ${colors.secondary400};
fill: ${colors.secondary400};
}
& ${Circle}:hover ${Polyline} {
stroke: #fff;
fill: ${colors.secondary400};
}
但是当悬停在圆上时折线仍然没有改变。我也试过嵌套:
& ${Circle}:hover {
stroke: ${colors.secondary400};
fill: ${colors.secondary400};
& ${Polyline} {
stroke: #fff;
fill: ${colors.secondary400};
}
}
似乎没有任何效果。我应该如何选择这条折线?
编辑:基于样式组件文档,我意识到在 Polyline 样式组件中处理这种样式可能会更好,因此我将以下内容放在一起:
const Polyline = styled.polyline`
pointer-events: none;
fill: #fff;
stroke: ${props => props.logged ? colors.secondary200 : colors.secondary400};
${Circle}:hover & {
stroke: #fff;
fill: ${colors.secondary400};
}
`;
这仍然不起作用,但是 ${Icon}:hover & { }
出于某种原因确实起作用了。我仍然无法使用它,因为 Icon
的边界在圆圈之外,但我完全不知道为什么 Polyline
响应悬停在 上>Icon
但不是 Circle
。 Circle
确实收到了悬停事件,因为它应用了自己的 :hover
样式。显然 Polyline 忽略了它。
参见 JSFiddle here
最佳答案
这是解决方案:https://jsfiddle.net/x9j7ku8o/3/
重要的一点是:
const Circle = styled.circle`
&:hover+${Polyline} {
stroke: #fff;
fill: #21ccbf;
}
`;
问题是您使用的是 descendant combinator (通过在 css 选择器中的 Circle 和 Polyline 之间使用空格),但 Polyline 不是 Circle 的后代。
Polyline 和 Circle 是兄弟,因此您必须使用其中一个兄弟组合器: adjacent sibling combinator或 general sibling combinator .我使用相邻的,因为折线和圆是相邻的。
重要的是要注意顺序很重要:我在 Circle
中使用组合符 &:hover+${Polyline}
因为在你的示例的 html 中,Circle 在 Polyline 之前。
关于css - 基于悬停选择 SVG 的另一部分不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57486417/