[英]how to move a div with arrow keys
var pane = $('#pane'), box = $('#box'), w = pane.width() - box.width(), d = {}, x = 3; function newv(v,a,b) { var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0); return n < 0 ? 0 : n > w ? w : n; } $(window).keydown(function(e) { d[e.which] = true; }); $(window).keyup(function(e) { d[e.which] = false; }); setInterval(function() { box.css({ left: function(i,v) { return newv(v, 37, 39); }, top: function(i,v) { return newv(v, 38, 40); } }); }, 20);
#pane { position: relative; width: 300px; height: 300px; border: 2px solid red; } #box { position: absolute; top: 140px; left: 140px; width: 20px; height: 20px; background-color: black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="pane"> <div id="box"></div> </div>
變量解釋:
w
- 框可以具有的最大左/上值(保持在邊界內)
x
- 盒子在每個間隔中移動的距離(以 px 為單位)
d
- 此對象存儲有關正在按下的鍵的信息。 例如,當用戶按住左箭頭鍵時, d['37']
為true
。 否則是false
。 順便說一句, 37
是左箭頭鍵的鍵碼,這個值存儲在事件對象的e.which
屬性中。 d
對象正在每個keydown
和keyup
事件上更新。
每 20 毫秒執行一次的 setInterval 更新 box 元素的 left 和 top CSS 屬性。 新值通過newv
函數計算。
newv
函數將根據 a) 舊值v
和 b) d
對象計算新的左/上值。
表達式n < 0 ? 0 : n > w ? w : n
n < 0 ? 0 : n > w ? w : n
n < 0 ? 0 : n > w ? w : n
確保新值在允許的范圍內(從0 to w
)。 如果 n < 0,則返回零。 如果 n > w,則返回 w。
更新:此代碼與上面的原始代碼具有相同的功能。 唯一的區別是我為變量和參數使用了更有意義的名稱。 如您所見,它看起來很糟糕 - 原始版本顯然更好。 :P
var pane = $('#pane'),
box = $('#box'),
maxValue = pane.width() - box.width(),
keysPressed = {},
distancePerIteration = 3;
function calculateNewValue(oldValue, keyCode1, keyCode2) {
var newValue = parseInt(oldValue, 10)
- (keysPressed[keyCode1] ? distancePerIteration : 0)
+ (keysPressed[keyCode2] ? distancePerIteration : 0);
return newValue < 0 ? 0 : newValue > maxValue ? maxValue : newValue;
}
$(window).keydown(function(event) { keysPressed[event.which] = true; });
$(window).keyup(function(event) { keysPressed[event.which] = false; });
setInterval(function() {
box.css({
left: function(index ,oldValue) {
return calculateNewValue(oldValue, 37, 39);
},
top: function(index, oldValue) {
return calculateNewValue(oldValue, 38, 40);
}
});
}, 20);
@Šime Vidas:您的第一個解決方案簡直太棒了。 (我認為第二個是多余的 =)
我可以建議為垂直和水平寬度制作兩個不同的功能嗎? 因為你必須在一個完美的正方形內移動一個 div 的可能性很小,我相信有這樣的東西會更好:
$(function () {
var pane = $('#pane'),
box = $('#box'),
wh = pane.width() - box.width(),
wv = pane.height() - box.height(),
d = {},
x = 5;
function newh(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > wh ? wh : n;
}
function newv(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > wv ? wv : n;
}
$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });
setInterval(function() {
box.css({
left: function(i,v) { return newh(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
}, 20);
});
這正是我正在尋找的。
如果您有基於 % 值的響應式設計,建議您像這樣調整 setInterval:
setInterval(function() {
box.css({
left: function(i,v) { return newh(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
wh = pane.width() - box.width();
wv = pane.height() - box.height();
}, 20);
如果你這樣做,它會調整你的窗格的高度和寬度,並且框仍然停在它的邊框處。
我在這里做了一個小提琴http://jsfiddle.net/infidel/JkQrR/1/
非常感謝。
我看不到您的演示,但這是一個簡單的“將框沿箭頭鍵方向移動 1px”的示例:
CSS:
#wrapper {
background-color: gray;
height:200px;
width: 200px;
position:absolute;
}
#mover {
background-color: white;
border: 1px solid red;
height:20px;
width: 20px;
position:relative;
}
標記:
<div id="wrapper">
<div id="mover"></div>
</div>
JS(使用 jQuery):
$("#wrapper").keydown(function(event) {
var $mover = $("#mover");
//if nothing else will move "mover", then track the
//position instead of recalculating it every time:
// var moverPos = $mover.position();
// var left = moverPos.left;
// var top = moverPos.top;
var addTop = function(diff) {
$mover.css("top", ($mover.position().top + diff) + "px");
//if using tracked position:
// top += diff;
// $mover.css("top", top) + "px");
};
var addLeft = function(diff) {
$mover.css("left", ($mover.position().left + diff) + "px");
//if using tracked position:
// left += diff;
// $mover.css("left", left) + "px");
};
switch(event.keyCode) {
case 37: //left
addLeft(-1); break;
case 38: //up
addTop(-1); break;
case 39: //right
addLeft(1); break;
case 40: //down
addTop(1); break;
}
});
這只是一個例子,你可能想要添加邊界檢查、更大的動作、更流暢的動畫、數字鍵盤支持或任何其他東西,但它應該讓你開始。
試試這個代碼
<html>
<head>
<style>
#ss{
background:#ccc;
height:100px;
width:100px;
position: absolute;
top: 0;
left: 0;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<div id="ss"></div>
</body>
<script type="text/javascript">
var $div = $('#ss');
$(document).keydown(function(e) {
switch (e.which) {
case 37:
$div.css('left', $div.offset().left - 10);
break;
case 38:
$div.css('top', $div.offset().top - 10);
break;
case 39:
$div.css('left', $div.offset().left + 10);
break;
case 40:
$div.css('top', $div.offset().top + 10);
break;
}
})
</script>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.