好吧,我制作了一个可以使用箭头键移动图像的页面,但只有向下和向右的功能有效。我从 hide show 脚本中创建了这些函数,因为我对 javascript 很陌生。
这是代码。
向左
function left(id) {
var y = '5';
var z =document.getElementById(id).style.left;
var x = parseInt(y)+parseInt(z);
var state = document.getElementById(id).style.left;
if (state == '1') {
document.getElementById(id).style.left = x;
} else {
document.getElementById(id).style.left = x;
}
}
右
function right(id) {
var y = '5';
var z =document.getElementById(id).style.right;
var x = parseInt(y)+parseInt(z);
var state = document.getElementById(id).style.right;
if (state == '1') {
document.getElementById(id).style.right = x;
} else {
document.getElementById(id).style.right = x;
}
}
向上
function up(id) {
var y = '5';
var z =document.getElementById(id).style.bottom;
var x = parseInt(y)+parseInt(z);
var state = document.getElementById(id).style.bottom;
if (state == '1') {
document.getElementById(id).style.bottom = x;
} else {
document.getElementById(id).style.bottom = x;
}
}
向下
function down(id) {
var y = '5';
var z =document.getElementById(id).style.top;
var x = parseInt(y)+parseInt(z);
var state = document.getElementById(id).style.top;
if (state == '1') {
document.getElementById(id).style.top = x;
} else {
document.getElementById(id).style.top = x;
}
}
然后是箭头键脚本
document.onkeyup = KeyCheck;
function KeyCheck() {
var KeyID = event.keyCode;
switch(KeyID)
{
case 37:
right('img');
break;
case 38:
up('img')
break
case 39:
left('img');
break;
case 40:
down('img');
break;
}
}
然后是 html
<img id="img" src="http://trevorrudolph.com/logo.png" style="position:absolute; left:1; bottom:1; right:1; top:1;">
您可以在 arrow.zip 下载 html
实际页面是here
最佳答案
您应该仅将其定位为 top
和left
,因为如果你尝试按照你正在做的方式去做,你最终会得到非常困惑的属性,例如 top
比如说 5 但有 bottom
比如说 100。
此外,您应该为 top
使用一个单位,最好是像素。和left
属性。
因此,您真正需要做的就是将函数更改为:
function left(id) {
document.getElementById(id).style.left.match(/^([0-9]+)/);
var current = RegExp.$1; // get just the number and not the units
document.getElementById(id).style.left = current - 1 + 'px'; // taking advantage of JavaScript's strange but sometimes useful type conversion. The subtraction converts it to an int and the addition converts it back to a string.
}
function right(id) {
document.getElementById(id).style.left.match(/^([0-9]+)/);
var current = RegExp.$1;
document.getElementById(id).style.left = parseInt(current) + 1 + 'px'; // here we can't use that trick
}
function up(id) {
document.getElementById(id).style.top.match(/^([0-9]+)/);
var current = RegExp.$1;
document.getElementById(id).style.top = current - 1 + 'px';
}
function down(id) {
document.getElementById(id).style.top.match(/^([0-9]+)/);
var current = RegExp.$1;
document.getElementById(id).style.top = parseInt(current) + 1 + 'px';
}
此外,您应该使用 <script type="text/javascript">
而不是<script language="JavaScript">
。后一种形式已被弃用。
关于javascript - 使用箭头键移动对象的 Html 和 java 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5253263/