Home > Mobile >  How to add an SVG hover event for text on a rectangle?
How to add an SVG hover event for text on a rectangle?

Time:10-20

I have an SVG with multiple rectangles which contain text. When hovering over a rectangle, I want to have a small shadow. Since one can't add text inside the rect element, I've added it after, which means that the text actually shows up on top of the rectangle, so when I hover over the text, the shadow isn't shown.

Since text is after rect, I can't use the sibling selector. I've also tried using a group, but with no success. Here is a small JSfiddle of what I'm trying to get (and the code).

<svg viewBox="0 0 100 100">
  <defs>
    <style>
      .slip {
        fill: blue;
      }
      .st {
        fill: white;
      }
      .slip:hover {
        cursor: pointer;
        -webkit-filter: drop-shadow(3px 3px 2px rgba(0, 0, 0, 0.7));
        filter: drop-shadow(3px 3px 2px rgba(0, 0, 0, 0.7));
      }
    </style>
  </defs>
  <g id="slips">
    <rect class="slip" x="10" y="10" width="80" height="50"/>
    <text class="st" x="20" y="30">1000</text>
  </g>
</svg>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

set the text to be pointer-events: none;

<svg viewBox="0 0 100 100">
  <defs>
    <style>
      .slip {
        fill: blue;
      }
      .st {
        fill: white;
        pointer-events: none;
      }
      .slip:hover {
        cursor: pointer;
        -webkit-filter: drop-shadow(3px 3px 2px rgba(0, 0, 0, 0.7));
        filter: drop-shadow(3px 3px 2px rgba(0, 0, 0, 0.7));
      }
    </style>
  </defs>
  <g id="slips">
    <rect class="slip" x="10" y="10" width="80" height="50"/>
    <text class="st" x="20" y="30">1000</text>
  </g>
</svg>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related