我正在尝试学习如何使用纯香草Javascript动画SVG。我想让圆圈变大和缩小,同时在每个圆圈的顶部显示一个标签,其值代表其当前尺寸。
Sor far我有以下SVG:
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
<path fill="none" d="M-1-1h502v302H-1z"/>
<g>
<path stroke-linecap="null" stroke-linejoin="null" stroke-opacity="null" stroke-width="4.5" stroke="#000" fill="none" d="M39.5 31.5v239M463.5 269.5l-422-1"/>
<ellipse stroke="#bf0000" ry="65.5" rx="67" cy="165" cx="158.5" stroke-width="4.5" fill="none"/>
<ellipse stroke="#007f00" ry="65.5" rx="67" cy="165" cx="361.5" stroke-width="4.5" fill="none"/>
</g>
</svg>
以下JS代码:
console.log("DOM Ready!");
var redCircle = document.getElementsByClassName('red');
var current = 0;
var destination = 700;
var friction = 0.04;
function loop() {
console.log(redCircle.style.width);
current += (destination - current) * friction;
redCircle.style.width = (current * 0.5 + 'px');
if (current >= destination - 0.1) {
clearInterval(animation);
}
}
var animation = setInterval(loop, 20);
我的问题是开发工具console.log说:
Uncaught TypeError: Cannot set property 'width' of undefined at loop
答案 0 :(得分:1)
document.getElementsByClassName返回一个数组而不是一个对象。你也没有名为&#39; red&#39;在你的html中,所以在你的脚本中返回的数组是= []。一个空数组。当你打电话给.style时,你基本上叫[] .style。由于样式不作为数组的属性存在(未定义)。然后你尝试获取不存在的东西([。。style)的属性(.width),这是不可能的,所以Javascript只能抛出错误。
console.log("DOM Ready!");
var redCircle = document.getElementsByClassName('red');
var current = 0;
var destination = 700;
var friction = 0.04;
function loop() {
// console.log(redCircle[0].style);
current += (destination - current) * friction;
redCircle[0].style.width = (current * 0.5 + 'px');
if (current >= destination - 0.1) {
clearInterval(animation);
}
}
var animation = setInterval(loop, 20);
&#13;
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg" class="red">
<path fill="none" d="M-1-1h502v302H-1z"/>
<g>
<path stroke-linecap="null" stroke-linejoin="null" stroke-opacity="null" stroke-width="4.5" stroke="#000" fill="none" d="M39.5 31.5v239M463.5 269.5l-422-1"/>
<ellipse stroke="#bf0000" ry="65.5" rx="67" cy="165" cx="158.5" stroke-width="4.5" fill="none"/>
<ellipse stroke="#007f00" ry="65.5" rx="67" cy="165" cx="361.5" stroke-width="4.5" fill="none"/>
</g>
</svg>
&#13;