【问题标题】:Selecting another part of the SVG based on hover isn't working基于悬停选择 SVG 的另一部分不起作用
【发布时间】: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 而不是CircleCircle 肯定会收到悬停事件,因为它应用了自己的 :hover 样式。显然折线忽略了它。

见 JSFiddle here

【问题讨论】:

    标签: css reactjs styled-components


    【解决方案1】:

    这里是解决方案: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 combinatorgeneral sibling combinator。我使用了相邻的,因为折线和圆是相邻的。

    重要的是要注意顺序很重要:我在Circle 中使用组合符&:hover+${Polyline},因为在您的示例html 中,Circle 位于 Polyline 之前。

    【讨论】:

    • 效果很好,非常感谢!当然,它最终只是一个简单的 CSS 问题,而不是一些疯狂的 React 诡计。
    猜你喜欢
    • 2013-07-28
    • 2015-09-20
    • 2021-09-29
    • 1970-01-01
    • 2018-12-18
    • 2020-07-13
    • 2017-04-12
    • 1970-01-01
    • 2016-05-21
    相关资源
    最近更新 更多