简体   繁体   中英

HTML5 and Javascript - a function appears to be working only once

guys, I am playing arround with HTML5 and 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. 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)

<!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(coil.style.left += 100 + "px");

the output is "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; coil.style.left= actualLeft +"px";

As nycynik mentioned, you are being a bit careless with the string additions.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM