timing javascript and src changes?
ok so i have this javascript to use the arrow ke开发者_运维技巧ys to send these javascripts when i press arrowkeys. i have a collaborating script that makes the right('img') command move the image but im trying to change the image as it moves with src changes and delays. Help?
<script type="text/javascript">
document.onkeydown = KeyCheck;
function KeyCheck(event) {
var spacebar=32
var KeyID = event.keyCode;
switch(KeyID) {
case 39:
right('img');
document.getElementById('img').src = 'guyr.png';
setTimeout("right('img');
document.getElementById('img').src = 'runr.png';
setTimeout("right('img');
document.getElementById('img').src = 'guyr.png';",100);",100);
break;
}
}
</script>
Changing the src
attribute of an image is going to trigger an asynchronous GET request, and may be slow at first before the browser has cached the images. It looks like you are implementing a game of some sort? Instead of changing the src
of a single image, I would keep all of the images hidden initially, and toggle the visibility
CSS attribute of images you want to show/hide. That way, you can pre-fetch all of the images that you'll need during load time, and simply show/hide elements as the handlers for your onkeydown
events.
If you want to do some sort of a game or animation, try to read a little about it, how to structure your game loop, animations and etc.
But if you are doing just some sort of test try something like this, is not a beautiful code but the idea of an animation should work:
document.onkeydown = KeyCheck;
function KeyCheck(event) {
var spacebar = 32;
var KeyID = event.keyCode;
switch (KeyID) {
case 39:
function guy(fn) {
right('img');
document.getElementById('img').src = 'guyr.png';
setTimeout(function() {
fn(guy);
}, 100);
}
function run(fn) {
right('img');
document.getElementById('img').src = 'runr.png';
setTimeout(function() {
fn(run);
}, 100);
}
guy(run);
break;
}
}
One function calls another, receiving it by parameter, in order to to continue the animation.
精彩评论