JavaScript使用箭头键移动图像 [英] JavaScript move an image with arrow keys
本文介绍了JavaScript使用箭头键移动图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经看到很多人在这里问类似的问题,但似乎没有一个对我有用.我有一个img,其ID为"character".我希望它在左键单击上向左移动,在右键单击上向右移动.这是我的代码:
I've seen lots of people ask similar questions here, but none of them seem to work for me. I have an img, with the id 'character'. I want it to move left on left click and right on right click. This is the code I have:
var bound = window.innerWidth;
function left(id) {
document.getElementById(id).style.left.match(/^([0-9]+)/);
var current = RegExp.$1;
if(current <=bound){
document.getElementById(id).style.left = current - 0 + 'px';
}
else{
document.getElementById(id).style.left = current - 5 + 'px';
}
}
function right(id) {
document.getElementById(id).style.left.match(/^([0-9]+)/);
var current = RegExp.$1;
if(current >= (bound - 5){
document.getElementById(id).style.left = current + 0 + 'px';
}
else{
document.getElementById(id).style.left = current + 1 + 'px';
}
}
document.onkeyup = KeyCheck;
function KeyCheck() {
var KeyID = event.keyCode;
switch(KeyID)
{
case 39:
right('character');
break;
case 37:
left('character');
break;
}
}
我不知道是否应该修复此代码,或者是否有更简单的方法.如果您有更简单的方法,请告诉我.
I don't know if I should fix this code, or if there is something simpler. If you have a simpler way of doing this, please let me know.
推荐答案
为什么不使用jQuery?
Why not use jQuery?
$("body").keydown(function(e) {
var max = $('body').width();
var min = 0;
var move_amt = 10;
var position = $("#my_image").offset();
if(e.which == 37) { // left
var new_left = ((position.left-move_amt < min) ? min : position.left-move_amt);
$("#my_image").offset({ left: new_left})
}
else if(e.which == 39) { // right
var new_left = ((position.left+move_amt > max) ? max : position.left+move_amt);
$("#my_image").offset({ left: new_left})
}
});
这是它的演示
这篇关于JavaScript使用箭头键移动图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文