我想使用jQuery通过箭头键移动IMG。我不知道如何在文档上使用方法。我不知道是否在switch语句的方法末尾使用括号。
<html>
<head>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script>
function moveIMG(event) {
var x = event.keyCode;
switch(x) {
case 37:
doLeft;
break;
case 38:
doTop;
break;
case 39:
doRight;
break;
case 40:
doBottom;
break;
}
}
function doTop() {
$("div").animate({top: '+=100px'},1200);
}
function doBottom() {
$("div").animate({bottom: '+=100px'},1200);
}
function doLeft() {
$("div").animate({left: '+=100px'},1200);
}
function doRight() {
$("div").animate({right: '+=100px'},1200);
}
</script>
</head>
<body onkeydown="myFunction(event)">
<div id="animateimg" style="position:absolute"><img src="black.png"></div>
<script>$(document).moveIMG()</script> <!-- I think in this place the problem -->
</body>
</html>
答案 0 :(得分:5)
尝试使用
$(document).on("keydown", moveIMG)
添加doLeft();
function moveIMG(event) {
var x = event.which; // use which instead in jQuery
switch (x) {
case 37:
doLeft(); // Add parens
break;
case 38:
doTop();
break;
case 39:
doRight();
break;
case 40:
doBottom();
break;
}
}
function doTop() {
$("div").animate({
top: '+=100px'
}, 1200);
}
function doBottom() {
$("div").animate({
bottom: '+=100px'
}, 1200);
}
function doLeft() {
$("div").animate({
left: '+=100px'
}, 1200);
}
function doRight() {
$("div").animate({
right: '+=100px'
}, 1200);
}
$(document).on("keydown", moveIMG);
<div id="animateimg" style="position:absolute">
<img src="//placehold.it/50x50/000">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
由于个人偏好,我不喜欢switch
这里的陈述是我的建议。通过使用预定义的Object文字来存储映射到 keyCode 整数的移动:
var keyMoves = {
37: {left: '-=100px'},
38: {top: '-=100px'},
39: {left: '+=100px'},
40: {top: '+=100px'},
};
function moveIMG (ev) {
ev.preventDefault();
$('div').stop().animate(keyMoves[ev.which], 1200);
}
$(document).on('keydown', moveIMG);
<div style="position:absolute"><img src="//placehold.it/50x50/000"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
http://api.jquery.com/on/
https://api.jquery.com/stop/
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics
答案 1 :(得分:3)
您必须将您的函数包装在实时侦听器(on
)中以捕获所有实时事件。调用函数时也使用括号。
$(document).on("keydown",function(e) {
var x = e.keyCode;
switch(x) {
case 37:
doLeft();
break;
case 38:
doTop();
break;
case 39:
doRight();
break;
case 40:
doBottom();
break;
}
})
答案 2 :(得分:1)
在`document:
上捕获您需要keydown
事件的箭头键
$(document).on("keydown", function(e) {
switch(e.keyCode) {
case 37: // left
doLeft();
break;
case 38: // up
doTop();
break;
case 39: // right
doRight();
break;
case 40: // down
doBottom();
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});