一种方法是使用 CSS 过渡 (*),但是您需要使用 fill:transparent 而不是 fill:none,如下所示 (1):
JS Fiddle 1
$(function() {
$('svg').hover(function() {
$('svg').find('.social-circle').stop()
.animate({'stroke-dashoffset': 0}, 1000)
.css({'fill': 'red', 'transition': 'fill 1s'});
console.log('on');
}, function() {
$('svg').find('.social-circle').stop()
.animate({'stroke-dashoffset': 900}, 1000)
.css({'fill': 'transparent', 'transition': 'fill 1s'});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="orange" class="social-circle" />
</svg>
你也可以使用.animate()函数提供的回调函数
.animate( properties [, duration ] [, easing ] [, complete ] )
其中“complete 是一个在动画完成后调用的函数,每个匹配的元素调用一次”,我们可以在这里调用另一个使用 CSS 动画填充元素的函数 transition 像这样:
JS Fiddle 2
$(function() {
$('svg').hover(function() {
$('svg').find('.social-circle').stop()
.animate({'stroke-dashoffset': 0}, 1000, animateFill('red'))
console.log('on');
}, function() {
$('svg').find('.social-circle').stop()
.animate({'stroke-dashoffset': 900}, 1000, animateFill('transparent'))
});
function animateFill(theColor) {
$('svg').find('.social-circle').css({'fill': theColor, 'transition': 'fill 1s'});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="orange" class="social-circle" />
</svg>
或者,您可以使用Snap.svg 实现相同的效果-支持 IE9+ 而 IE10 及更高版本支持CSS 过渡- 使用它的 animate() (*) 函数,但是当我尝试传递 animFill('transparent') 或 animFill('none') 时,它默认颜色为黑色而不是透明。所以我让这个函数同时为fill 和fill-opacity (2) 设置动画,这样它就可以用于过渡颜色或填充不透明度。如下:
JS Fiddle 3
$(function() {
$('svg').hover(function() {
$('svg').find('.social-circle').stop()
.animate({'stroke-dashoffset': 0}, 1000, animFill('red', 1));
console.log('on');
}, function() {
$('svg').find('.social-circle').stop()
.animate({'stroke-dashoffset': 900}, 1000, animFill('red', 0))
});
});
function animFill(theColor, theOpacity) {
Snap('svg').select('.social-circle')
.animate({'fill': theColor,'fill-opacity': theOpacity}, 1000);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/snap.svg/0.4.1/snap.svg-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="orange" class="social-circle" id="social" />
</svg>
----------------------------------------------- ----------------------------------
(*)对于 CSS 过渡和 Snap.svg 动画,您可以像 jQuery 一样使用缓动。对于 CSS,可以这样做:
transition: fill 1s ease-out
对于 Snap.svg,可以通过 mina() 方法设置缓动,同上:
element.animate({'fill':theColor, 'fill-opacity':theOpacity}, 1000, mina.easeout);
(1)为了简单起见,我删除了缓动。
(2)通过使用fill-opacity,我们只控制fill的不透明度,如果我们使用opacity,整个元素将被影响为fill和stroke。还有stroke-opacity也可以控制笔画的不透明度。