我使用了YouTube教程。我不明白为什么它不起作用。出于某种原因,当我按A
或D
时,没有任何反应。
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container{
position: relative;
height: 600px;
width: 400px;
outline: 2px solid black;
}
#character{
position: absolute;
height: 50px;
width: 50px;
outline: 2px solid black;
background-color: #FF6600;
left: 0;
}
</style>
<body onkeydown="anim">
<div id="container">
<div id="character"></div>
</div>
<script>
var container = document.getElemnetById('container');
var character = document.getElemnetById('character');
var characterLeft = 0;
function anim(e){
if (e.keyCode == 97){
characterLeft += 2;
character.style.left = characterLeft + 'px';
}
if (e.keyCode == 100){
characterLeft -= 2;
character.style.left = characterLeft + 'px';
}
}
</script>
</body>
</head>
</html>
`
答案 0 :(得分:0)
使用此
<div id="pop" onclick="anim();">
<span>click me</span>
<div id="container">
<div id="character">
</div>
</div>
<script>
var container = document.getElemnetById('container');
var character = document.getElemnetById('character');
var characterLeft = 0;
function anim()
{
alert('yes it work!!');
if (e.keyCode == 97){
characterLeft += 2;
character.style.left = characterLeft + 'px';
}
if (e.keyCode == 100){
characterLeft -= 2;
character.style.left = characterLeft + 'px';
}
}
</script>
</div>
答案 1 :(得分:0)
这很有效。我还交换了关键效果 - 按下&#34; a&#34;将框移到左侧并按下&#34; d&#34;将它移到右边。希望这可以帮助。 GAV
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#container
{
position: relative;
height: 600px;
width: 400px;
outline: 2px solid black;
}
#character
{
position: absolute;
height: 50px;
width: 50px;
outline: 2px solid black;
background-color: #FF6600;
left: 0;
}
</style>
<body>
<div id="container">
<div id="character"></div>
</div>
<script>
var container = document.getElementById('container');
var character = document.getElementById('character');
var characterLeft = 0;
document.onkeypress = function (e) {
e = e || window.event;
var charCode = e.charCode || e.keyCode;
if (charCode == 97){
characterLeft -= 2;
character.style.left = characterLeft + 'px';
};
if (charCode == 100){
characterLeft += 2;
character.style.left = characterLeft + 'px';
}
}
</script>
</body>
</head>
</html>