在鼠标悬停时使用文本更改颜色制作svg多边形按钮?

时间:2021-11-29 19:29:23

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.

我更喜欢使用html / css,但只要我不需要另一个库,我就可以使用javascript / jquery。

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 :(
  • 将文本元素放在多边形元素中,但这是不允许的。无法在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 :(
  • 当文本悬停在文本上时使用CSS来定位多边形,但是您无法定位上一个兄弟。 CSS可以针对下一个兄弟但不是之前:(

  • 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 :(
  • 将文本元素放在多边形之前然后使用CSS下一个兄弟来在文本悬停时定位多边形,但我不能在文本上使用z-index,因此您无法看到文本。 svg中没有z-index支持:(

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

我觉得这很简单......我遇到了一些恼人的限制。

2 个解决方案

#1


6  

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

您可以使用 嵌套svg的元素:

<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:

然后应用CSS样式:

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

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

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

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

#2


0  

You can use:

您可以使用:

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

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

Updated Fiddle

#1


6  

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

您可以使用 嵌套svg的元素:

<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:

然后应用CSS样式:

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

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

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

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

#2


0  

You can use:

您可以使用:

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

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

Updated Fiddle