Jquery按键/向下和动画

时间:2012-07-20 09:09:31

标签: jquery jquery-animate keypress keydown

我试图让div左右移动,但我的动画似乎被忽略了...任何想法我做错了什么?

JS:

$(document).ready(function(){            
    $(document).keydown(function (e) {
        var keyCode = e.keyCode || e.which,
        arrow = {left: 37, up: 38, right: 39, down: 40 };

        switch (keyCode) {

            case arrow.left: 
                $('#block').animate({"left": "-=1px"}, "slow");
            break;

            case arrow.right: 
                $('#block').animate({"left": "+=1px"}, "slow");
            break;
        }
    });
});

CSS:

body{
    font-family:arial, verdana;
    color:#000;
    font-size:12px;
}

#block {
    width:50px;
    height:50px;
    border:1px solid #ff0000;
}

http://jsfiddle.net/AeWEc/

2 个答案:

答案 0 :(得分:2)

#block设为position:absoluteposition: relative,这意味着提供一些position属性。

#block {
    width:50px;
    height:50px;
    border:1px solid #ff0000;
    position:absolute
}

<强> DEMO

因为动画中的left更改了元素的left CSS属性,而left属性适用于CSS position

答案 1 :(得分:1)

检查更新JSFiddle

body{
    font-family:arial, verdana;
    color:#000;
    font-size:12px;
}

#block {
    width:50px;
    height:50px;
    border:1px solid #ff0000;
    position:absolute;
    top:0;
    left:0;
}