我刚接触JS,所以可能会缺少一些东西。我试图用鼠标悬停为SVG矩形设置动画,以使形状看起来像是在“逃离”鼠标。当我尝试通过添加x和y来更改它们时,形状消失了。如果我减去,它的表现将达到预期。
任何帮助将不胜感激。
HTML
<svg width="1200" height="600">
<rect x="100" y="100" width="100" height="100" id="firstShape" onmouseover="moveShape(firstShape);">
</svg>
Javascript
function moveShape(obj) {
var newX = obj.getAttribute("x") + 5;
var newY = obj.getAttribute("y") + 5;
obj.setAttribute("x", newX);
obj.setAttribute("y", newY);
}
属性是字符串,而Javascript处理字符串和数字的方式非常草率。
您实际上所做的是将“ 5”添加到“ 100”,结果是“ 1005”。
如果您在修改属性之前将属性转换为整数,那么您的代码将可以正常工作。
function moveShape(obj) {
var newX = parseInt(obj.getAttribute("x")) + 5;
var newY = parseInt(obj.getAttribute("y")) + 5;
obj.setAttribute("x", newX);
obj.setAttribute("y", newY);
}
<svg width="1200" height="600">
<rect x="100" y="100" width="100" height="100" id="firstShape" onmouseover="moveShape(firstShape);">
</svg>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句