0

我正在尝试让 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/

4

2 回答 2

2

让你#block成为position:absoluteor position: relative,这意味着赋予一些position属性。

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

演示

因为,left在动画中改变left元素的 CSS 属性,并且left属性适用于 CSS position

于 2012-07-20T09:12:51.433 回答
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;
}
于 2012-07-20T09:14:58.327 回答