سؤال

http://jsfiddle.net/J7psN/

<svg viewbox='0 0 80 80'>
    <polygon id=button points='50,0 80,80 0,80'/>
    <text x=40 y=50>HELLO</text>
</svg>

I have a polygon button with text on it and I want the polygon to get brighter when you hover over it. The problem is that when you hover over the text, the polygon goes back to dark.

I'd prefer to use mostly html/css but I'm fine with using javascript/jquery as long as I don't need another library.

I was hoping to do one of the following to solve it:

  • Putting the text element inside the polygon element, but that isn't allowed. Can't nest elements in svg :(
  • Using CSS to target the polygon when the text is hovered over, but you can't target the previous sibling. CSS can target next sibling but not previous :(
  • Putting the text element before the polygon then use CSS next sibling to target the polygon when the text is hovered, but I can't use z-index on the text so you then can't ever see the text. No z-index support in svg :(

I thought this would be simple... I've run into some annoying limitations.

هل كانت مفيدة؟

المحلول

You can nest elements of an svg using <g>:

<svg viewbox='0 0 80 80'>
  <g id=button>
    <polygon points='50,0 80,80 0,80'/>
    <text x=40 y=50>HELLO</text>
  </g>
</svg>

and then apply css styling:

#button {
  cursor: pointer;
  fill: #900;
}

#button:hover {
  cursor: pointer;
  fill: #F00;
}

text {
  font-size:7px;
  fill: black;
}

See: http://jsfiddle.net/J7psN/1/

نصائح أخرى

You can use:

$( "#button" ).hover(
  function() {
    $(this).css('fill' ,'#F00');
  }, function() {
    $(this).css('fill' ,'#900');
  }
);

$('text').mouseover(function(e) {
    $(this).prev().mouseover();
});

Updated Fiddle

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top