SVG “fill: url(#…)” behaving strangely in Firefox

2019-01-22 19:29发布

I have the following SVG graphic:

<svg width='36' height='30'>
  <defs>
    <linearGradient id="normal-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:rgb(81,82,84); stop-opacity:.4"/>
      <stop offset="100%" style="stop-color:rgb(81,82,84); stop-opacity:1"/>
    </linearGradient>
    <linearGradient id="rollover-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:rgb(0,105,23); stop-opacity:.5"/>
      <stop offset="100%" style="stop-color:rgb(0,105,23); stop-opacity:1"/>
    </linearGradient>
    <linearGradient id="active-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:rgb(0,0,0); stop-opacity:.4"/>
      <stop offset="100%" style="stop-color:rgb(0,0,0); stop-opacity:1"/>
    </linearGradient>
  </defs>

  <text x="8" y="25" style="font-size: 29px;" font-family="Arial">hello world</text>
</svg>'

I set the fill attribute of the text element through CSS and switch between the various gradients depending on the hover state. This works great in Chrome & Safari, but in Firefox, the text doesn't show up. Upon inspecting the element, I discovered that Firefox is appending none to the end of my fill: url(#...) CSS attribute. I tried deleting the none keyword with Firebug, but Firebug just deletes the entire attribute. Why is this happening?

EDIT: I should note that if I remove the CSS that sets the fill property, and hardcode the fill attribute into the text element (not through an inline style attribute), the text displays properly in all browsers.

3条回答
▲ chillily
2楼-- · 2019-01-22 20:02

Figured it out. In my CSS, I was referring to the gradients in the same way I was originally referencing the fill inline:

#myselector {
    fill: url('#gradient-id');
}

To get it working in Firefox, I had to change it to this:

#myselector {
    fill: url('/#gradient-id');
}

Not sure why this is. Maybe it has something to do with the directory structure containing my stylesheet?

查看更多
叛逆
3楼-- · 2019-01-22 20:12

I had same problem with linearGradient in SVG – still in 2017. I guess, the problem is that Firefox treat url('#gradient-id') like normal URL and applied rules of <base href=""/> metatag. Comment it out and check then.

查看更多
戒情不戒烟
4楼-- · 2019-01-22 20:15

SVG “fill: url(#…)” behave strangely in Firefox when we assigning the below code with css(both external and internal css.)

#myselector {
fill: url('#gradient-id');
}

Solution

give inline styling, this can be done in both the ways. Static or dynamic way

Dynamic way

.attr('fill', 'url(#gradient-id)')

Static way

fill="url(#gradient-id)" 

In static you have to put this in the SVG Html;

查看更多
登录 后发表回答