我的档案:
index.html
client
css
style.css
js
javascript.js
的index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>blablabla</title>
<link rel="stylesheet" type="text/css" href="client/css/style.css">
<script type="text/javascript" src="client/js/javascript.js"></script>
</head>
<body>
<div id="container">
<div id="guy"></div>
</div>
</body>
</html>
javascript.js
var guy=document.getElementById('guy');
var container=document.getElementById('container');
var guyLeft=0;
function anim(e){
if(e.keyCode==39){
guyLeft +=2;
guy.style.left = guyLeft + 'px';
}
if(e.keyCode==37){
guyLeft -=2;
guy.style.left = guyLeft + 'px';
}
}
document.onkeydown =anim;
的style.css
#container{
height:400px;
width:600px;
outline:1px solid black;
position: relative;
}
#guy{
position: absolute;
height:50px;
width:50px;
outline:1px solid black;
background-color:red;
left:0;
}
1)所以大家请帮忙..我只是想左右移动对象..当我把这个代码放在index.html之间时它可以工作但是在单独的javascript.js类中不起作用。求助。
答案 0 :(得分:2)
1)您必须在页面底部加载JavaScript。
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>blablabla</title>
<link rel="stylesheet" type="text/css" href="client/css/style.css">
</head>
<body>
<div id="container">
<div id="guy"></div>
</div>
<script type="text/javascript" src="client/js/javascript.js"></script>
</body>
</html>
2)上下移动:
var guy = document.getElementById('guy');
var container = document.getElementById('container');
var guyLeft = 0;
var guyTop = 0;
function anim(e){
if(e.keyCode==39){
guyLeft +=2;
guy.style.left = guyLeft + 'px';
}
if(e.keyCode==37){
guyLeft -=2;
guy.style.left = guyLeft + 'px';
}
// UP
if(e.keyCode==38) {
guyTop -=2;
guy.style.top = guyTop + 'px';
}
// DOWN
if(e.keyCode==40) {
guyTop +=2;
guy.style.top = guyTop + 'px';
}
}
document.onkeydown = anim;
如果你想捕捉JavaScript中的错误和错误,你应该使用console。