Javascript 在屏幕上随机、连续地移动div
我正在尝试使用jQuery使div四处移动- HTML:Javascript 在屏幕上随机、连续地移动div,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正在尝试使用jQuery使div四处移动- HTML: <body> <div class="random"></div> <button class="play">Click Me!"</button> </body> body { background-color: red; margin: 0; padding: 0; } .random { background-
<body>
<div class="random"></div>
<button class="play">Click Me!"</button>
</body>
body {
background-color: red;
margin: 0;
padding: 0;
}
.random {
background-color: black;
height: 5px;
width: 5px;
}
$(document).ready(function() {
var playing = false;
var top;
var left;
var i;
// the button controls the play start/stop, based on "playing"
$('.play').click(function() {
if(!playing) {
// if not playing, start playing around 10 times...
playing = true;
for(i=0; i<10; i++) {
setTimeout(function() {
top = Math.floor((Math.random() * 100) + 1);
left = Math.floor((Math.random() * 100) + 1);
$('.random').offset({top: top, left: left});
}, 1000);
}
} else {
// if playing, stop the play and return to 0,0...
playing = false;
top = left = 0;
$('.random').offset({top: top, left: left});
}
});
});
JS:
<body>
<div class="random"></div>
<button class="play">Click Me!"</button>
</body>
body {
background-color: red;
margin: 0;
padding: 0;
}
.random {
background-color: black;
height: 5px;
width: 5px;
}
$(document).ready(function() {
var playing = false;
var top;
var left;
var i;
// the button controls the play start/stop, based on "playing"
$('.play').click(function() {
if(!playing) {
// if not playing, start playing around 10 times...
playing = true;
for(i=0; i<10; i++) {
setTimeout(function() {
top = Math.floor((Math.random() * 100) + 1);
left = Math.floor((Math.random() * 100) + 1);
$('.random').offset({top: top, left: left});
}, 1000);
}
} else {
// if playing, stop the play and return to 0,0...
playing = false;
top = left = 0;
$('.random').offset({top: top, left: left});
}
});
});
$(文档).ready(函数(){
var=false;
var-top;
左var;
var i;
//该按钮根据“播放”控制播放开始/停止
$('.play')。单击(函数(){
如果(!玩){
//如果不玩,开始玩10次左右。。。
玩=真;
对于(i=0;i)每次迭代的超时时间为1000
。您可能需要执行类似(100*i)的操作
对于你的timeouttry来说,这就像一个符咒,尽管我不太理解100*I部分。我观察到的另一件事是,按钮在迭代过程中卡住了。它是否必须等待迭代完成?