Html:如何使用箭头键动态移动图像?

时间:2015-04-09 19:55:56

标签: html css image dynamic position

我正在尝试使用CSS在我的命令(箭头键)上移动图像。

我想到了这个:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<script>
    function a() {
    // k is a global variable but i dont know how to declare it
        document.getElementById("img1").style.top = k + "px";
        k++;
        // and also i dont know how to trigger the function using the arrow keys
    }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <img id="img1" src="IMAGES/logo.jpg" height="100" width="100"
           style="position:absolute; left:100px; top:100px; z-index:1" />
    </div>
    </form>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

您可以使用JavaScript来使用onkeypress事件来捕获键盘上的按键事件。

例如:

<input type="text" onkeypress="myFunction()">

答案 1 :(得分:0)

以下是演示:http://jsfiddle.net/nhYN3/36/

$("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})
  }
});

Source

答案 2 :(得分:0)

仅限JavaScript(没有jQuery),它看起来像这样:

document.addEventListener("keydown", moveImage, false);

var img = document.getElementById('img1');
//The amount of pixels to move the image by with each keypress.
var moveJump = 10;

function moveImage(e) {
    var kc = e.keyCode;
    //Gets the current "top" value minus the "px" as an int.
    var top = parseInt(img.style.top.substr(0, img.style.top.length - 2));
    //Gets the current "left" value minus the "px" as an int.
    var left = parseInt(img.style.left.substr(0, img.style.left.length - 2));

    switch (kc) {
        case 37:
            //Pressed left.
            img.style.left = (left - moveJump) + 'px';
            break;
        case 38:
            //Pressed up.
            img.style.top = (top - moveJump) + 'px';
            break;
        case 39:
            //Pressed right.
            img.style.left = (left + moveJump) + 'px';
            break;
        case 40:
            //Pressed down.
            img.style.top = (top + moveJump) + 'px';
            break;
    }
}

小提琴:http://jsfiddle.net/auwchLdn/2/