<!DOCTYPE html>
<html lang="en">
<head>
<style>
#move{
width: 20px;
height: 20px;
background-color: red;
}
</style>
<meta charset="UTF-8" />
<title>move</title>
</head>
<body>
<div id ="move"></div>
<script type = 'text/javascript'>
window.onload = moveMessage();
function moveMessage(){
var elem = document.getElementById('move');
elem.style.position ="absolute";
elem.style.left = "20px";
elem.style.top = "30px";
// 没有加引号
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
if (xpos == 2002&&ypos == 2002) {
return ture;
}
if (xpos<200) {
xpos++;
}
if (xpos > 200) {
xpos --;
}
if (ypos<200) {
ypos++;
}
if (ypos > 200) {
ypos --;
}
elem.style.left=xpos+'px';
elem.style.top = ypos +'px';
movement = setTimeout('moveMessage()',100)
}
</script>
</body>
</html>
<!DOCTYPE html> <html lang="en"> <head> <style> #move{ width: 20px; height: 20px; background-color: red; } </style> <meta charset="UTF-8" /> <title>move</title> </head> <body> <div id ="move"></div> <script type = 'text/javascript'> var elem = document.getElementById('move'); elem.style.position ="absolute"; elem.style.left = "20px"; elem.style.top = "30px"; window.onload = moveMessage(); function moveMessage(){ var elem = document.getElementById('move'); //elem.style.position ="absolute"; //这里每次都重置了,所以看不到效果,我把他放到上面了 //elem.style.left = "20px"; //elem.style.top = "30px"; // 没有加引号 var xpos = parseInt(elem.style.left); var ypos = parseInt(elem.style.top); if (xpos == 2002&&ypos == 2002) { return ture; } if (xpos<200) { xpos++; } if (xpos > 200) { xpos --; } if (ypos<200) { ypos++; } if (ypos > 200) { ypos --; } elem.style.left=xpos+'px'; elem.style.top = ypos +'px'; movement = setTimeout('moveMessage()',10) } </script> </body> </html>
感谢,我还想问一下
function moveMessage(){};
下面函数调用的时候,函数后面 加和不加括号 有什么不同吗
window.onload = moveMessage();
window.onload = moveMessage;
@nostic: 这样用的时候都行
因为函数在js里面是一个对象