我試圖移動我的角色(保存在變量'player'下,它絕對定位。)當我按'W','A','S'和'D'鍵。但我無法讓它移動。任何幫助都會很棒。按鍵上的Javascript:player.style.left + = 10,不知道爲什麼這不起作用
let player;
let bod;
player_one_horizontal_position;
window.onload = function(){
bod = document.getElementsByTagName('body');
player = document.getElementById('player');
player_one_horizontal_position = 10;
bod.addEventListener('keydown',function(e){
if(e.code === 'KeyA'){
player_one_horizontal_position += 10;
check_position(e.code);
};
}); //end of eventListener
}//end of window.onload function
function check_position(code){
console.log(code === 'KeyA'); /*does evaluate to true so the problem must be the next line */
player.style.left = player_one_horizontal_position;
}
我已經在本週早些時候就做過類似的事情用jQuery所以我不知道這是爲什麼不與香草JS工作
HTML:
<!DOCTYPE html>
<html>
<head>
<!-- Main stylesheets -->
<link rel="stylesheet" href="style.css"/>
<!-- Player stylesheets -->
<link rel="stylesheet" href="player_one.css"/>
<link rel="stylesheet" href="player_two.css"/>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<div id="player" class="stance_one"></div>
<div id="player2" class="first_stance"></div>
</div>
</body>
</html>
的CSS球員之一:
#player{
background-image: url('images/sprite.png');
position: absolute;
z-index: 1;
height: 142px;
left: 10;
}
.stance_one{
width: 8%;
background-position: 0% 0%;
}
'left'必須有一個單元。 – SLaks
你能提供更多的上下文嗎? (例如HTML,CSS) – Trevor
@Trevor是的,現在包含相關的html和css –