首页 新闻 赞助 找找看

为什么我这段移动元素位置的代码没有效果啊,控制台也没有报错》

0
悬赏园豆:10 [已解决问题] 解决于 2016-04-13 10:07

<!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>

nostic的主页 nostic | 初学一级 | 园豆:160
提问于:2016-04-12 08:56
< >
分享
最佳答案
0
<!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>

 

收获园豆:10
刘宏玺 | 专家六级 |园豆:14020 | 2016-04-12 09:26

感谢,我还想问一下

function moveMessage(){};

下面函数调用的时候,函数后面 加和不加括号 有什么不同吗

window.onload = moveMessage();

window.onload = moveMessage;

nostic | 园豆:160 (初学一级) | 2016-04-13 10:16

@nostic: 这样用的时候都行

因为函数在js里面是一个对象

刘宏玺 | 园豆:14020 (专家六级) | 2016-04-13 13:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册