简体   繁体   English

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

[英]Make svg polygon button with text change color on mouseover?

http://jsfiddle.net/J7psN/ 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来定位多边形,但是您无法定位上一个兄弟。 CSS can target next sibling but not previous :( 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. 将文本元素放在多边形之前然后使用CSS下一个兄弟来在文本悬停时定位多边形,但是我不能在文本上使用z-index,因此您无法看到文本。 No z-index support in svg :( svg中没有z-index支持:(

I thought this would be simple... I've run into some annoying limitations. 我觉得这很简单......我遇到了一些恼人的限制。

You can nest elements of an svg using <g> : 您可以使用<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/ 请参阅: 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM