jQuery一点一点地在屏幕上移动一个div

Bar*_*der 3 html jquery jquery-ui

所以我有这个代码:

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

问题是我只能按"a"一次而#character只移动一次......

我还启用了jQuery draggable(http://jqueryui.com/demos/draggable/),周围有一个约束区域.

为什么我只能用按键移动div一次?

Poi*_*nty 9

I don't think that jQuery will interpret that "+=40" on a call to .css(). I suspect that it only moves once because the first time you blast away whatever the "left" value originally was and set it to the string "+=40", which the browser ignores. Subsequent clicks just repeat that.

I might be wrong, but I've been reading the jQuery source and I see nothing to suggest that the .css() function does what .animate() does with values like that.

You might try using .animate() directly:

case 97:    $('#character').animate({'left': '+=40'}, 1);
Run Code Online (Sandbox Code Playgroud)