我目前正在嘗試制作一個 html 游戲,玩家可以在其中移動網頁,但我無法讓移動作業。我希望玩家在按鍵時繼續前進。我讓按鍵作業,我用警報測驗了它,但我不能讓它移動 div。這是我的代碼,
function keyPress(){
if(window.event.keyCode == 87){
document.getElementById("player").style.left = 10 'px';
}
if(window.event.keyCode == 83){
alert("spressed")
}
if(window.event.keyCode == 65){
alert("apressed")
}
if(window.event.keyCode == 68){
alert("dpressed")
}
}
.player{
background-color: black;
height: 50px;
width: 50px;
}
<!doctype html>
<html onkeydown="keyPress()">
<head>
<link rel="stylesheet" href="lib/style.css">
<script src="lib/script.js"></script>
</head>
<body>
<div class="player" id="player">
</div>
</body>
</html>
這對你們中的一些人來說可能很容易,所以我很感激你的幫助。謝謝 : )
uj5u.com熱心網友回復:
這里的問題是.player該類沒有屬性,您必須像這樣position定義位置absolute
position: absolute;
如果要設定元素相對于其包含塊的位置,或使用
position: fixed;
設定元素相對于初始包含塊的位置。
作業片段
function keyPress(){
if(window.event.keyCode == 87){
document.getElementById("player").style.left = 10 'px';
}
if(window.event.keyCode == 83){
document.getElementById("player").style.left = 50 'px';
}
if(window.event.keyCode == 65){
document.getElementById("player").style.left = 100 'px';
}
if(window.event.keyCode == 68){
document.getElementById("player").style.left = 150 'px';
}
}
.player{
position: fixed;
background-color: black;
height: 50px;
width: 50px;
}
<!doctype html>
<html onkeydown="keyPress()">
<head>
<link rel="stylesheet" href="lib/style.css">
<script src="lib/script.js"></script>
</head>
<body>
<div class="player" id="player">
</div>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/516335.html
上一篇:我有一個ReactHookuseEffect缺少依賴項:
下一篇:如何以訊息樣式格式對齊?
