JQuery moves div around screen differently

So, I have this code:

$(document).ready(function() {
            $(document).keypress(function(e)
            {
                switch(e.which)
                {
                    // user presses the "a"
                    case 97:    $('#character').css('left','+=40');
                }
            }
}

The problem is that I can only press "a" once, and #character only moves once ...

I also have jQuery draggable ( http://jqueryui.com/demos/draggable/ ) enabled with a limited environment around it.

Why can I only move the div once by pressing a key?

+3
source share
4 answers

, jQuery "+ = 40" .css(). , , , "" "+ = 40", . .

, , jQuery, , , .css() , .animate() , .

.animate() :

case 97:    $('#character').animate({'left': '+=40'}, 1);
+9

.css(), .

:

       // The 'left' parameter in the function references the current position.

case 97:$('#character').css('left',function(i,left){
                                    return parseInt(left) + 40;
                                });

: @Gaby, .replace('px','') , .parseInt() .

+1

I think you will need to get the character’s position, add 40 to the left, and then apply a css change, for example

var pos = $("#character").offset();

$("#character").animate({"left": pos.left + 40}, 100);

If you save the position of the symbol in another place, you can also simply update this value and update its position in the game loop.

0
source

I am surprised that he does anything at all!

your missing pair); and I also changed it a bit. it works!

$(document).ready(function () {
    $(document).keypress(function (e) {
        switch (e.which) {
            // user presses the "a"   
            case 97:
                var left = parseInt($('#character').css('left')) + 40;

                $('#character').css('left', left + 'px');
        }
    });
});
0
source

Source: https://habr.com/ru/post/1754809/


All Articles