0

我需要使用箭头键在屏幕上移动火柴人图片。我似乎无法找到如何。我已经尝试了我发现的所有东西,但仍然没有用。这是链接

代码:

<script>
     $(document).ready(function(){
        $('#sitting').hide();  
            $(document).keydown(function(e){
                var keyCode = e.keyCode || e.which,
                    arrow = { left:37, up:38, right: 39, down: 40 };
                switch (keyCode {
                case arrow.left:
                    if(!$('#sitting').is(':visible')){
                    $('#img,#sitting').animate({
                        left:'-=60px'
                    },300,"linear");
                    }
                break;
                case arrow.up:
                break;
                case arrow.right:
                    if(!$('#sitting').is(':visible')){
                    $('#img,#sitting').animate({
                        left:'+=60px'
                    },300,"linear");
                    }
                break;
                case arrow.down:
                break;
                }
            });
        $('#sit').click(function(){
            $('#img').fadeToggle(-100,function(){
                $('#sitting').fadeToggle(-100);
            });
        });
    }); 
    </script>
    <button id='left'><<</button><button id='right'>>></button><button id='sit'>Sit Down/Stand up</button><br />
    <img src='/jquery/sprites/spritePerson.png' id='img' style='position: absolute; margin-top: 375px;' /><img id='sitting' src='/jquery/sprites/spriteSitting.png' style='position: fixed; margin-top: 375px;'><img id='tree' src='/jquery/sprites/spriteTree.png' style='position: absolute; margin-top: 100px; margin-left: 700px;' /><br />
4

1 回答 1

0

Think your code to be working . only you missed a bracket code in switch (keyCode).

How ever you need to work around your code. some of your code can be optimized.

like.

  1. Always use stop(true) before you call animate method. This stops the queue of animate . like $(selector).stop(true).animate({});
  2. Why you need to make a new object of arrow . you can directly use key code in case;

  3. make a reference to your selector so it will not traverse all the time to get element.

see jsfiddle : http://jsfiddle.net/bxAtd/

于 2013-02-03T04:55:22.327 回答