gpt4 book ai didi

javascript - 用箭头键改变图像?

转载 作者:行者123 更新时间:2023-12-02 15:43:24 26 4
gpt4 key购买 nike

我有一个使用箭头键在屏幕上移动的图像。我想知道如何更改每个键移动的图像。

我意识到图像附加到每个 Action 上。 Action 并未附加到每张图像上。

这是我所拥有的:

<script type="text/javascript">

function leftArrowPressed() {var element = document.getElementById("image1");
element.style.left = parseInt(element.style.left) - 10 + 'px';}

function rightArrowPressed() {var element = document.getElementById("image1");
element.style.left = parseInt(element.style.left) + 10 + 'px';}

function upArrowPressed() {var element = document.getElementById("image1");
element.style.top = parseInt(element.style.top) - 10 + 'px';}

function downArrowPressed() {var element = document.getElementById("image1");
element.style.top = parseInt(element.style.top) + 10 + 'px';}


function moveSelection(event) {
switch (event.keyCode) {
case 37:leftArrowPressed();break;
case 39:rightArrowPressed();break;
case 38:upArrowPressed();break;
case 40:downArrowPressed();break;
}
};


function gameLoop()
{
// change position based on speed
moveSelection();
setTimeout("gameLoop()",10);
}

</script>
</head>

<body onload="gameLoop();" onkeydown="moveSelection(event)" onkeyup="moveSelection(event)"'>

<img id="image1" src="images/casual.png" style="position: absolute; left: 15; right: 15; top: 15; bottom: auto; " height="20" width="16">
</body>

最佳答案

在每个 ArrowPressed() 函数中,只需将元素的 src 更改为您想要的每个箭头键即可:

function downArrowPressed() {
var element = document.getElementById("image1");
element.style.top = parseInt(element.style.top) + 10 + 'px';
element.src = "imageForDownArrow.png";
}

function upArrowPressed() {
var element = document.getElementById("image1");
element.style.top = parseInt(element.style.top) - 10 + 'px';
element.src = "imageForUpArrow.png";
}

function leftArrowPressed() {
var element = document.getElementById("image1");
element.style.left = parseInt(element.style.left) - 10 + 'px';
element.src = "imageForLeftArrow.png";
}

function rightArrowPressed() {
var element = document.getElementById("image1");
element.style.left = parseInt(element.style.left) + 10 + 'px';
element.src = "imageForRightArrow.png";
}

关于javascript - 用箭头键改变图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32419604/

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