[英]HTML5 and Javascript - a function appears to be working only once
guys, I am playing arround with HTML5 and javascript. 伙计们,我在玩HTML5和javascript。 The current thing which I am making is the following: there is a purple block on the screen and when you click a button it is moved 100 pixels to the right. 我当前正在做的事情如下:屏幕上有一个紫色块,当您单击按钮时,它向右移动了100像素。 This works so far, however, the function works only on the first time it is ran. 到目前为止,此功能仍然有效,但是该功能仅在首次运行时有效。 I can't find my bug. 我找不到我的错误。 I am posting the entire source code (javascript, html and css) 我正在发布整个源代码(javascript,html和css)
<!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>
When you do your add like that, its not actually adding to the value, its only making a new string; 当您像这样进行添加时,它实际上并没有添加到值中,而只是添加了一个新字符串。 add a console.log on the button and you will see. 在该按钮上添加console.log,您将看到。
console.log(coil.style.left += 100 + "px");
the output is "100px100px" 输出为“ 100px100px”
one alternative solution: 一种替代解决方案:
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");
}
You must use a closure. 您必须使用闭包。 A variable in the closure context must keep the left value. 闭包上下文中的变量必须保留左值。 Then when applying the value to the property you use 然后,将值应用于您使用的属性
var actualLeft += 100; var actualLeft + = 100; coil.style.left= actualLeft +"px"; coil.style.left = ActualLeft +“ px”;
As nycynik mentioned, you are being a bit careless with the string additions. 正如nycynik所提到的,您对字符串的添加有些粗心。
Try this: 尝试这个:
function clickHandler2()
{
var before = parseInt(coil.style.left);
before = isNaN(before) ? 0 : before;
coil.style.left = before + 100 + "px";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.