【发布时间】:2019-12-20 12:32:15
【问题描述】:
我有一个 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};
}
}
似乎没有任何效果。我应该如何选择这条折线?
编辑:根据样式组件文档,我意识到在折线样式组件中处理此样式可能会更好,因此我将以下内容放在一起:
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 样式。显然折线忽略了它。
见 JSFiddle here
【问题讨论】:
标签: css reactjs styled-components