2015-04-23 71 views
2

我刚刚进入JS,所以我可能会错过一些东西。我正在尝试使用鼠标悬停对SVG矩形进行动画处理,以便形状看起来像是在“逃离”鼠标。当我尝试通过添加它们来更改x和y时,形状消失。如果我减去,它的行为如预期。Javascript动画 - SVG形状消失

任何帮助将不胜感激。

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); 
     } 

回答

2

属性是字符串,Javascript对处理字符串和数字的方式非常sl sl。

你实际上做的是将“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>

+0

非常感谢。这工作完美。 – user3602839

+0

@ user3602839没问题:-)顺便说一下,如果有可能这些坐标不是整数,那么使用'parseFloat()'而不是'parseInt()'。 –