如何在CSS中悬停时选择兄弟元素?

时间:2016-06-02 21:37:00

标签: css svg

我似乎无法弄清楚如何在突出显示文本时让rect元素将颜色更改为紫色。相反,只有文本颜色在变化。有没有办法只使用CSS?

当文本悬停时,

Rect应将其颜色更改为紫色。

.chart rect {
  //fill: steelblue;
  stroke: black;
}
.x.axis path {
  display: none;
}
text {
  text-anchor: middle;
  alignment-baseline="middle";
}
rect:hover {
  fill: purple;
}
rect ~ text:hover {
  fill: purple
}
<svg class="chart" width="800" height="60">
  <g transform="translate(108.2258064516129,30)">
    <rect width="206.4516129032258" height="29" fill="orange"></rect>
    <text x="103.2258064516129" y="15" dy=".35em">ABB vs BBA</text>
    <text x="103.2258064516129" y="-20" dy=".35em" style="fill: black;">Round 2</text>
  </g>
</svg>

1 个答案:

答案 0 :(得分:4)

而不是填充

rect ~ text:hover {
  fill: purple;
}

...使用pointer-events: none

rect ~ text {
  pointer-events: none;
}

即使鼠标悬停在文本上,也会将焦点保持在矩形内。

<强>段:

.chart rect {
  //fill: steelblue;
  stroke: black;
}
.x.axis path {
  display: none;
}
text {
  text-anchor: middle;
  alignment-baseline="middle";
}
rect:hover {
  fill: purple;
}
rect ~ text {
  pointer-events: none;
}
<svg class="chart" width="800" height="60">
  <g transform="translate(108.2258064516129,30)">
    <rect width="206.4516129032258" height="29" fill="orange"></rect>
    <text x="103.2258064516129" y="15" dy=".35em">ABB vs BBA</text>
    <text x="103.2258064516129" y="-20" dy=".35em" style="fill: black;">Round 2</text>
  </g>
</svg>