如何在SVG中此三角形的悬停效果中添加文本?

时间:2019-04-03 17:28:38

标签: html css svg

我制作了一个具有悬停效果的三角形,但是我无法添加文本。如何在此多边形的悬停效果内添加文本?

html:

<svg version="1.0" id="formas" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 792 612" enable-background="new 0 0 792 612" xml:space="preserve">
   <linearGradient id="triangulo_apartado_1_1_" gradientUnits="userSpaceOnUse" x1="0" y1="252.5721" x2="117.5039" y2="252.5721">
      <stop  offset="0" style="stop-color:#5D676A"/>
      <stop  offset="0.4845" style="stop-color:#808B91"/>
      <stop  offset="1" style="stop-color:#5D676A"/>
   </linearGradient>
   <polygon class="triangle" id="triangulo_apartado_1"  fill="url(#triangulo_apartado_1_1_)"stroke="#FFFFFF" stroke-miterlimit="10" points="117.504,281.948 0,281.948 58.752,223.196"/>
</svg>

css中的样式:

.triangle{} .triangle:hover{fill:#ffcd00;}

1 个答案:

答案 0 :(得分:1)

您在三角形之后立即创建一个文本元素。文字中有fill-opacity:0; 当您将鼠标悬停在三角形上时,文本的不透明度变为1:

.triangle:hover + text{fill-opacity:1;pointer-events:none}

text{fill-opacity:0;}
.triangle:hover{fill:#ffcd00;}
.triangle:hover + text{fill-opacity:1;pointer-events:none}
<svg version="1.0" id="formas" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 792 612" enable-background="new 0 0 792 612" xml:space="preserve">
   <linearGradient id="triangulo_apartado_1_1_" gradientUnits="userSpaceOnUse" x1="0" y1="252.5721" x2="117.5039" y2="252.5721">
      <stop  offset="0" style="stop-color:#5D676A"/>
      <stop  offset="0.4845" style="stop-color:#808B91"/>
      <stop  offset="1" style="stop-color:#5D676A"/>
   </linearGradient>
   <polygon class="triangle" id="triangulo_apartado_1"  fill="url(#triangulo_apartado_1_1_)"stroke="#FFFFFF" stroke-miterlimit="10" points="117.504,281.948 0,281.948 58.752,223.196"/>
   
 <text x="35" y="270" >triangle</text>
</svg>