2015-02-09 96 views
1

首先,我已经看到很多答案在移植过程中,但没有一个能够帮助我!我想从一个随机的位置开始我的div,然后它会移动。而是从静态位置显示出来,然后进入随机位置,然后开始移动。我想声明我顶部和Div并非从随机位置开始

$(document).ready(function() 

由JavaScript离开,但它不能帮助

HTML

<div class="ballarea" id="ballarea1"> 
     <div class="circle type" id="ball"></div> 
    </div> 

CSS

.circle{ 
border-radius: 50%; 
border: thin; 
border-color: blue; 
} 
.type { 
width: 20px; 
height: 20px; 
border: 5px solid blue; 
position: relative; 
} 

.ballarea{ 
width: 300px; 
height: 400px; 
border: solid black; 
overflow: hidden; 
position: relative; 
} 

的JavaScript

var i=0; 
var j=0; 
function ballMove(){ 
var d=document.getElementById("ball"); 
var temp=i; 
if(i<1) 
{ 
    i = Math.floor(Math.random() * (200)); 
    j = Math.floor(Math.random() * (200)); 

} 
for(;i<2+temp;i++,j++) 
{ 
    d.style.left=i+"px"; 
    d.style.top=j+"px"; 
} 
//document.getElementById('ball').style.display = 'block'; 

} 

function timeChange() 
{ 
setInterval(ballMove, 500); 
} 

enter image description here

现在首先它像下面,然后将其从一个随机位置开始静止位置开始。我想从一个不是从静态位置的随机位置展示它

+0

成立了小提琴,请 – 2015-02-09 07:16:39

+0

你尝试先隐藏,然后显示在随机位置后,它被设置? – Royalty 2015-02-09 07:17:11

回答

0

尝试先隐藏它,因为脚本在DOM准备就绪时运行。

<div class="ballarea" id="ballarea1"> 
     <div class="circle type" id="ball" style="display:none"></div> 
    </div> 

然后你的脚本运行时,表现出来

var i = 0; 
var j = 0; 
function randomBall(){ 
    var d = document.getElementById("ball"); 
    i = Math.floor(Math.random() * (200)); 
    j = Math.floor(Math.random() * (200)); 
    d.style.left = i+"px"; 
    d.style.top = j+"px"; 
    d.style.display = "block"; 
} 

function ballMove(){ 
    var d=document.getElementById("ball"); 
    i += 2; 
    j += 2; 
    d.style.left = i+"px"; 
    d.style.top = j+"px"; 
} 

function timeChange() 
{ 
    randomBall(); 
    setInterval(ballMove, 500); 
} 
+0

我试过了。这是行不通的。和以前一样。 – 2015-02-09 07:49:32

+0

我不太明白你想用这个'var temp = i来达到什么目的; if(i <1) {'and this'for(; i <2 + temp; i ++,j ++) {' – 2015-02-09 07:53:24

+0

这有助于移动。每次我增加时(我首先将它初始化为0),并且我希望它每500ns移动2 px,因此我更新了i,并且因为我希望它移动比当前i值多2的px。所以我把价值存储在温度(因为每次迭代我越来越多,我不能把我放在条件它将无限) – 2015-02-09 08:08:25