所以我尝试使用键盘上的方向键移动元素。它会移动,但是一旦我切换方向(水平 || 垂直),它就会在程序加载时重新建立之前的方向原始位置。因此,如果元素开始于 margin-top
& margin-left
at 100px
一旦元素被移动,则水平离开坐标现在为 MT = 100px
& ML = 150px
一旦我切换到垂直元素 ML 变为 100。这不是我想要发生的,我想要的是元素 ML & MT 代表它之前的操作。从 100&100 移动到 150&100,然后移动到 150&150。加上没有图书馆的,直接的 JS。
var spacePos = 5;
var spaceNeg = -5;
var output;
var marginLeft =1;
var marginTop =1;
function init(){
output = document.getElementById('output');
document.onkeydown = updateKeys;
}
updateKeys = function(e){
currentKey = e.keyCode;
output.innerHTML = "current key: " + currentKey;
if (currentKey=='39') {
marginLeft = marginLeft + spacePos;
document.getElementById('blockB').style='margin-left:' + marginLeft +'px';
}
else if (currentKey=='37') {
marginLeft = marginLeft + spaceNeg;
document.getElementById('blockB').style='margin-left:' + marginLeft +'px';
}
else if (currentKey=='38') {
marginTop = marginTop + spaceNeg;
document.getElementById('blockB').style='margin-top:' + marginTop +'px';
}
else if (currentKey=='40') {
marginTop = marginTop + spacePos;
document.getElementById('blockB').style='margin-top:' + marginTop +'px';
}
}
K_LEFT = 37;
K_RIGHT = 39;
K_UP = 38;
K_DOWN = 40;
#blockB{
width:10px;
height:10px;
margin-top:100px;
margin-left:100px;
position:absolute;
background-color: blue;
}
<body onload='init()'>
<div id='output'> </div>
<div id='blockB'> </div>
</body>
最佳答案
基本上你的问题是你只是在使用箭头时设置 margin-left
或 margin-right
,这是错误的,因为:
从前 100 名开始,剩下 100 名。
如果你从左向右移动,你只设置
margin-left
,假设你移动了 100 个单位,你的新左边是 200。style { margin-left: 200px
如果你开始从上到下移动,只设置
margin-top
比方说 50 个单位,你的新顶部是 150。style { margin-top: 150px }
(使用初始值left=100
作为默认值
但您没有考虑到您需要同时设置它们,以便该元素始终具有从顶部和底部开始的轨道。
另请注意,您在每个 if 中设置样式,您可以进行计算,然后在末尾设置值。
另外注意,开始使用let
和const
,再这样下去你的代码会变得一团糟。
var spacePos = 5;
var spaceNeg = -5;
var output;
var marginLeft = 100;
var marginTop = 100;
function init() {
output = document.getElementById('output');
document.onkeydown = updateKeys;
}
updateKeys = function(e) {
currentKey = e.keyCode;
output.innerHTML = "current key: " + currentKey;
if (currentKey == '39') {
marginLeft = marginLeft + spacePos;
} else if (currentKey == '37') {
marginLeft = marginLeft + spaceNeg;
} else if (currentKey == '38') {
marginTop = marginTop + spaceNeg;
} else if (currentKey == '40') {
marginTop = marginTop + spacePos;
}
document.getElementById('blockB').style = 'margin:' + marginTop + 'px ' + marginLeft +
'px';
}
K_LEFT = 37;
K_RIGHT = 39;
K_UP = 38;
K_DOWN = 40;
<script>
</script>
<body onload='init()'>
<div id='output'> </div>
<div id='blockB'> </div>
</body>
<style>
#blockB {
width: 10px;
height: 10px;
margin-top: 100px;
margin-left: 100px;
position: absolute;
background-color: blue;
}
</style>
关于javascript - 使用键盘上的键操作元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54259748/