javascript - Div 不是从随机位置开始的

标签 javascript html css

首先,我在 stakeoverflow 中看到了很多答案,但这些都没有帮助我!!!我想从一个随机位置开始我的 div,然后它会移动。而不是它从一个静态位置显示,然后它到达一个随机位置,然后它开始移动。我试图在

中通过 javascript 声明我的顶部和左侧
$( document ).ready(function()

但这并没有帮助

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

现在,它首先从如下所示的静态位置开始,然后从随机位置开始。我想从随机位置而不是静态位置显示它

最佳答案

首先尝试隐藏它,因为您的脚本会在 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);
}

关于javascript - Div 不是从随机位置开始的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28404556/

相关文章:

javascript - jQuery Append 删除/隐藏以前的对象

javascript - 隐藏表格中的长文本但保持对它的访问

css - 如何为响应式表格提供自动宽度

html - H1如何防止继承?

html - 将滚动条添加到没有设置高度的 div

javascript - 为什么我的模态 jQuery 对话框会打开多次?

javascript - 在javascript中混合字符串的中间

css - 按空格键时防止 Visual Studio 2013 退出编辑类标记

javascript:如何检查属性未定义

javascript - Css 在悬停时上下滑动 div 的图像