gpt4 book ai didi

javascript - 如何在 keydown 上编码多个键? (javascript)

转载 作者:行者123 更新时间:2023-11-28 15:00:56 26 4
gpt4 key购买 nike

我试图让每个键在按下时对应不同的图像。 (例如:按下“A”时=出现图像1,按下“S”时=出现图像2,依此类推。)

我能够让“S”键工作,但不能让A键工作。我正在尝试对键盘上的整行执行此操作(“A”,“S”,“D”,“F” ","G","H","J","K","L")

*PS。我还是个初学者:)

这是我的代码:

<img src="images/giphy.gif" width="800" height="400" alt=""/>

<script>
document.addEventListener("keydown", keyDownBody, false);

function keyDownBody(e) {
var keyCode = e.keyCode;
if(keyCode==65) {
myFunction();
}
}

function myFunction() {
var x = document.createElement("IMG");
x.setAttribute("src", "images/giphy1.gif")
x.setAttribute("width", "800");
x.setAttribute("height", "400");
x.setAttribute("alt", "The Pulpit Rock");
document.body.appendChild(x);
}

function keyDownBody(e) {
var keyCode = e.keyCode;
if(keyCode==83) {
myFunction();
}
}

function myFunction() {
var x = document.createElement("IMG");
x.setAttribute("src", "images/sun.gif")
x.setAttribute("width", "800");
x.setAttribute("height", "400");
x.setAttribute("alt", "The Pulpit Rock");
document.body.appendChild(x);
}
</script>

最佳答案

您已多次声明同一个函数。您可以合并它们以使其正常工作,并使您的代码更具可读性。一个例子:

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

function keyDownBody(e) {
var keyCode = e.keyCode;
switch (keyCode) {
case 65:
loadImage("images/giphy1.gif", "The Pulpit Rock");
break;
case 83:
loadImage("images/sun.gif", "The Pulpit Rock");
break;

// Etc.
}
}

function loadImage(uri, alt) {
var x = document.createElement("IMG");
x.setAttribute("src", uri)
x.setAttribute("width", "800");
x.setAttribute("height", "400");
x.setAttribute("alt", alt);
document.body.appendChild(x);
}

这样您就可以添加任意数量的键。

或者,如果将图像放入数组中,则可以动态加载图像:

var images = [{
uri: 'images/giphy1.gif',
alt: 'A',
}, {
uri: 'images/sun.gif',
alt: 'Some text',
},
// Etc.
];

function keyDownBody(e) {
var keyCode = e.keyCode;

var index = keyCode - 65;
if (typeof images[index] !== 'undefined')
{
var image = images[index];
loadImage(image.uri, image.alt);
}
}

关于javascript - 如何在 keydown 上编码多个键? (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40981932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com