2012-05-16 88 views
2

這個功能有什麼問題?用javascript移動圖像

function moveColor() 
{ 
document.getElementById(purple).style.marginRight = "34px"; 
} 

與這個網站:

<div><img src="images/purple.png" id="purple" onclick="colorpurple()" onmouseover="moveColor()" style="cursor:pointer;"/></div> 

我也想擁有它移動一段1秒,但似乎無法來解決這個簡單的問題。

+0

(沒有在頁面中間的示例代碼) – dnsmkl

+0

什麼「是否想讓它在1秒內移動」是指?你想讓它滑過?您可以使用[CSS3轉換](http://css3.bradshawenterprises.com/transforms/)或[jQuery Animate](http://api.jquery.com/animate/)輕鬆完成。 –

+0

我也建議jQuery,所有你需要做的是:'$('#purple')。animate({'margin-right':'34px'},1000)' –

回答

5

您需要將ID放在引號中(,以便將它視爲字符串)。

document.getElementById('purple').style.marginRight = "34px"; 

當前使用意味着purple是指一個變量,它不是定義,因此它有一個undefined值,所以document.getElementById方法返回什麼..

0

好像你錯過了功能引號的getElementById。

像這樣:

function moveColor() { 
     document.getElementById('purple').style.marginRight = "34px"; 
} 
你可能要考慮的jQuery`animate`功能http://api.jquery.com/animate/