2013-05-17 50 views
2

夥計們,我正在用HTML5和javascript玩遊戲。目前我正在做的事情如下:屏幕上有一個紫色塊,當你點擊一個按鈕時,它會向右移動100像素。這工作到目前爲止,然而,該功能只在第一次運行。我找不到我的錯誤。我張貼的全部源代碼(JavaScript的HTML和CSS)HTML5和Javascript - 一個函數似乎只能工作一次

<!doctype html> 
<head> 
<style> 
#stage{ 
    position: relative; 
    width : 800px; 
    height : 600px; 
    background: #c0c0c0; 
    border: 1px dashed black; 
} 

.coil{ 
    width: 64px; 
    height: 64px; 
    background: #800080; 
    position: absolute; 
    top: 200px; 
    left: 50px; 
} 
</style> 
</head> 


<body> 
<div id="stage"> 
<div class="coil"></div> 
<button id="button1">move!</button> 
</body> 
<script> 
var coil = document.querySelector(".coil"); 
var button = document.querySelector("#button1"); 
button.addEventListener("click", clickHandler2, false); 

//why is it working correctly just once 
function clickHandler2() 
{ 
    coil.style.left += 100 + "px"; 
} 
</script> 
+3

每次要追加字符串 '100px的' 到'coil.style.left'財產。所以在第二次點擊你有無效的CSS。 – XGundam05

+0

好的,我該如何解決這個問題? – Bloodcount

+1

只是一些注意事項:1.你沒有'html'標籤。 2.你不關閉'#stage'標籤。 3.你把'script'放在'body'之外,並且它是HTML無效的。 – 2013-05-17 16:46:29

回答

2

正如nycynik所說,你對字符串的添加有點粗心。

試試這個:

function clickHandler2() 
{ 
    var before = parseInt(coil.style.left); 
    before = isNaN(before) ? 0 : before; 
    coil.style.left = before + 100 + "px"; 
} 
+0

謝謝,當系統讓我時,我會將其標記爲答案。 – Bloodcount

+1

這裏是一個工作小提琴:http://jsfiddle.net/FAf4Q/(一些微調需要雖然...) – WheretheresaWill

2

當你做你的插件那樣,它沒有實際增加值,其僅在進行一個新的字符串;在按鈕上添加一個console.log,你會看到。

console.log(coil.style.left += 100 + "px"); 

輸出爲 「100px100px」

一個替代的解決方案:

var coilPos = 100; 
//why is it working correctly just once 
function clickHandler2() 
{ 
    coilPos += 100; 
    coil.style.left = coilPos + "px"; 
    console.log(coil.style.left += 100 + "px"); 
} 
2

您必須使用封閉。閉包上下文中的變量必須保留左值。然後,將值應用到您使用的財產

var actualLeft + = 100; coil.style.left = actualLeft +「px」;