2015-04-23 70 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()'。 –