【发布时间】:2014-04-06 13:16:50
【问题描述】:
我有一个 div,我正在尝试使用 jQuery 制作动画。我的目标是根据相应的按键向左、上、右和下移动 div。
例如,如果我按左箭头键,则 div 会向左移动等。
目前,当页面加载/刷新时,我的 div 能够向左、向右、向上和向下移动。但是,一旦我将 div 向右移动,我就无法将其向左移动,当我将其向下移动时,我无法将其向上移动,依此类推......
如何让我的 div 在各个方向上更流畅?
jsfiddle:http://jsfiddle.net/6U6cA/4/
我的代码
HTML:
<body>
<div id="container">
<div id="switcher">
<div class="label">TestDiv</div>
<button id="switcher-default">Default</button>
<button id="switcher-large">Default 1</button>
<button id="switcher-small">Default 2</button>
</div>
</div>
</body>
CSS:
#switcher {
width: 300px;
padding: .5em;
border: 1px solid #777;
}
.label {
width: 130px;
margin: .5em 0;
cursor: pointer;
}
jQuery:
$(document).ready(function() {
$('#switcher').css({
position:'relative',
display:'inline-block'
});
$(document).keyup(function(event){
var key=event.which;
switch(key){
case 37:
$('#switcher').animate({right:'+=20'});
break;
case 38:
$('#switcher').animate({bottom:'+=20'});
break;
case 39:
$('#switcher').animate({left:'+=20'});
break;
case 40:
$('#switcher').animate({top:'+=20'});
break;
}
});
【问题讨论】:
标签: javascript jquery css