SVG animations won't work after import as a ba

2019-07-28 23:04发布

I was playing with an SVG which was supposed to do some animations if you hovered over it. The animations themselves worked perfectly, but when I wanted to import that svg as a background-image in my CSS the animations just wouldn't happen, is there something I'm doing wrong?

The animations were made in the SVG file, here's the code:

<?xml-stylesheet type="text/css" href="svg.css" ?>
<svg version="1.1" id="Layer_5" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 309.3 248.5" style="enable-background:new 0 0 309.3 248.5;" xml:space="preserve">


<style type="text/css">
.st0{fill:none;stroke:#DDDDDD;stroke-width:4;stroke-miterlimit:10;}


.st0
{
fill: #DDDDDD;
}



svg:hover .st0
{
stroke: #38B2AE;
stroke-dasharray: 2500;
stroke-dashoffset: 0;    
-webkit-animation: dash 4s linear forwards;
-o-animation: dash 4s linear forwards;
-moz-animation: dash 4s linear forwards;
animation: dash 4s linear forwards;

-webkit-transition: fill 2s ease;
-moz-transition: fill 2s ease;
-o-transition: fill 2s ease;
transition: fill 2s ease;
fill: #38B2AE;
}

@-webkit-keyframes dash {
from {
    stroke-dashoffset: 2500;
    }
to {
    stroke-dashoffset: 0;
    }
}

@-o-keyframes dash {
from {
    stroke-dashoffset: 2500;
    }
to {
    stroke-dashoffset: 0;
    }
}

@-moz-keyframes dash {
from {
    stroke-dashoffset: 2500;
    }
to {
    stroke-dashoffset: 0;
    }
}

@keyframes dash {
from {
    stroke-dashoffset: 2500;
    }
to {
    stroke-dashoffset: 0;
    }
}

My HTML is:

<header id="homenav">
<a class="logo" href="#index.html">Homepage</a>

And the CSS:

.logo
{
background-image: url(../images/logo2.svg);
width: 75px;
height: 60px;
margin-left: 15px;
text-indent: -9999px;
margin-bottom: 15px;
display: block;
margin-left: auto;
margin-right: auto;
}

I do see the file but the animations won't work.

标签: html css svg
1条回答
三岁会撩人
2楼-- · 2019-07-28 23:08

If the animations require user interaction to trigger them, they won't work as background image (or as HTML <img>). User events are never passed to image contents.

One possible workaround: Create two different versions of the SVG, one without animation, and one with the animations set to start automatically. Then use CSS :hover pseudoclass to switch between the two background images.

Edit: As Robert Longson warns in the comments, however, the start times of the animation won't necessarily coordinate with the switch to using that image on hover. In many browsers, the unused background image still persists in memory, and animations are not automatically re-started when the image is used again.

If you want more control over the animation as it relates to user events, but still want the SVG to be in a separate file from the main page, use an <object> in the HTML code.

查看更多
登录 后发表回答