2

伙计们,我正在玩 HTML5 和 javascript。我正在制作的当前内容如下:屏幕上有一个紫色块,当您单击一个按钮时,它会向右移动 100 个像素。到目前为止,这有效,但是,该功能仅在第一次运行时有效。我找不到我的错误。我正在发布整个源代码(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>
4

3 回答 3

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");
}
于 2013-05-17T16:43:31.100 回答
2

您必须使用闭包。闭包上下文中的变量必须保持左值。然后在将值应用于您使用的属性时

var实际左+= 100;线圈.style.left=实际左+“px”;

于 2013-05-17T16:44:31.730 回答
2

正如 nycynik 提到的,您对字符串添加有点粗心。

尝试这个:

function clickHandler2()
{
    var before = parseInt(coil.style.left);
    before = isNaN(before) ? 0 : before;
    coil.style.left = before + 100 + "px";
}
于 2013-05-17T16:44:33.513 回答