【问题标题】:SVG "circle" element radius attribute "r" does not transition in Firefox but does just fine in ChromeSVG“圆”元素半径属性“r”在 Firefox 中没有过渡,但在 Chrome 中效果很好
【发布时间】:2017-02-06 07:09:54
【问题描述】:

我正在尝试在单击事件上使 SVG 圆圈变大,它在 Chrome 52 中运行良好(尚未在旧版本上尝试过),但在 Firefox 中,CSS 过渡没有效果。有没有办法在没有太多 JavaScript 的情况下让 Firefox 的行为与 Chrome 相同?

HTML:

<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <circle cx="50%" cy="50%" r="15"/>
</svg>

CSS:

html, body {
        height: 100%;
        width: 100%;
        margin: 0;
        padding: 0;
    }
    circle {
        -webkit-transition: ease 0.7s all;
        -moz-transition: ease 0.7s all;
        -ms-transition: ease 0.7s all;
        -o-transition: ease 0.7s all;
        transition: ease 0.7s all;
    }

JS:

$(document).ready(function() {
    $("body").click(function() {
        if($("circle").attr("r") == 15) {
            $("circle").attr("r", function() {
                if ($(window).height() > $(window).width()) {
                    return Math.sqrt(Math.pow($(window).width(), 2) + Math.pow($(window).height(), 2));
                }
                return (Math.sqrt(Math.pow($(window).width(), 2) + Math.pow($(window).height(), 2)));
            });
        } else {
            $("circle").attr("r", 15);
        }
    });
});

https://jsfiddle.net/xgscn4f1/

【问题讨论】:

  • 如果你不想使用 javascript,你可以在 Firefox 的 SMIL 中写这个。

标签: javascript html css svg


【解决方案1】:

在当前标准 SVG 1.1 中,只有某些属性可以通过 CSS 设置样式。这些属性的列表可以在这里找到:

SVG 1.1 property index

请注意,r 不在此列表中。

在即将发布的 SVG2 标准中,大多数属性都可以设置样式。但是浏览器才刚刚开始实现 SVG2 功能。现在您可以在 Chrome 中修改和转换 r,但在其他浏览器中尚不能。

您将需要使用另一种技术为r 设置动画。要么使用 SVG SMIL 动画,要么使用具有动画功能的各种 SVG JS 库之一。

【讨论】:

  • 有什么 SVG JS 库推荐吗?
  • 我没有任何建议。有很多数字可供选择,但我一个都没用过。
【解决方案2】:

您可以使用纯 JS 轻松为 SVG 元素的任何属性设置动画,包括圆的半径,只需为元素提供 ID:

var c1 = document.getElementById("c1");
var strokeLength = 300;
c1.setAttribute("stroke-dasharray", "" + (strokeLength) + " 700");

function changeR(el) {
	var n1 = 0;
	var ch1 = 1;
	var elT = setInterval(elTF, 5);
	function elTF() {
		el.setAttribute("r", n1);
		if (n1 == 0) {
			ch1 = 1;
		} else if (n1 == 100) {
			ch1 = -1;
		}
		n1 += ch1;
	}
}
changeR(c1);
<svg width="250" height="200">		
  <circle id="c1" cx="100" cy="100" r="50" fill="transparent" stroke="blue" stroke-width="10" stroke-linecap="butt" stroke-dasharray="300 500" />
</svg>

也可以动画笔画长度,通过“stroke-dasharray”属性,第一个参数,第二个是空白。

【讨论】:

    猜你喜欢
    • 2020-08-16
    • 2020-12-07
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    相关资源
    最近更新 更多