![](/img/trans.png)
[英]Move Div left/right and Up/Down by clicking on another div in JQuery
[英]Animated Div goes right and left, but not up and down
我有一個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;
}
});
首先要設置left
樣式屬性,然后是right
,但這是行不通的,因為沒有刪除left
因此它覆蓋了right
樣式。
堅持使用一個CSS屬性
$(document).ready(function () {
$('#switcher').css({
position: 'relative',
display: 'inline-block'
});
$(document).keyup(function (event) {
var key = event.which;
switch (key) {
case 37:
$('#switcher').animate({
left: '-=20'
});
break;
case 38:
$('#switcher').animate({
top: '-=20'
});
break;
case 39:
$('#switcher').animate({
left: '+=20'
});
break;
case 40:
$('#switcher').animate({
top: '+=20'
});
break;
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.