1

If I take out the variable counter and just set document.getElementById("movee").style.top equal to a number, it works fine. Combining the variable counter and that bit of code would theoretically get an image to move. It's not working for some reason though!

<html>
<style type="text/css">
    #movee
    {
        position:absolute;
    }
</style>

<script type="text/javascript">
    function goDown()
    {
        var counter=1; 
        while (counter<300)
        {
            document.getElementById("movee").style.top="counter";
            var counter=counter+1;
        }
    }
</script>

<input type="button" onclick="goDown()" value="Move!">
<img src="test.png" id="movee"></img>
</html> 
4

3 回答 3

4

You're setting the top style property of #movee to the string "counter" not the value of the variable counter

document.getElementById("movee").style.top=counter+"px";

Also it seems you are trying to animate the element, your technique will not work as the update will occur only after your script finish running. I suggest looking into css transitions, or a library that does animations like jQuery(jQuery.animate).

于 2013-02-23T19:27:47.503 回答
0

remove the quotes from "counter" and after that line do not use "var counter", just counter +=1

于 2013-02-23T19:27:28.397 回答
0

Even if your code to set the top style was correct, your element wouldn't animate because the code doesn't return control to the browser during the loop. Instead it would appear to move all 300 pixels at once.

于 2013-02-23T19:28:41.413 回答