[英]Why this very simple javascript/jquery code won't work correctly
I have a very simple JavaScript/jquery code which won't just work correctly. 我有一个非常简单的JavaScript / jquery代码,它不能正常工作。 The problem seems to be that positioning of the div with id 'circle' does not seem to get calculated when the loop is run.
问题似乎是在运行循环时似乎没有计算id为'circle'的div的定位。 Just need to know why the problem is occurring and if any fixes available.
只需知道问题发生的原因以及是否有任何修复方法。
Here is the link http://jsfiddle.net/TDRyS/ Basically what I am trying to do is trying to move the ball up once it is at a distance of 500px from the top. 这里是链接http://jsfiddle.net/TDRyS/基本上我要做的是尝试在距离顶部500px的距离时将球移动。
The code: 编码:
var maxa = document.width;
var maxb = document.height;
$(document).ready(function() {
dothis();
});
function dothis() {
var left = parseInt(document.getElementById('circle').style.left);
var top = parseInt(document.getElementById('circle').style.top);
if (top >= 500) {
$("#circle").animate({
top: "-=" + Math.floor(Math.random() * 100 + 1) + "px",
left: "-=" + Math.floor(Math.random() * 100 + 1) + "px"
}, 1000);
}
else {
$("#circle").animate({
top: "+=" + Math.floor(Math.random() * 100 + 1) + "px",
left: "+=" + Math.floor(Math.random() * 100 + 1) + "px"
}, 1000);
}
dothis();
}
You need to setTimeout before calling the function again\\ pass the function as a callback 在再次调用函数之前需要setTimeout \\将函数作为回调函数传递
Full code: 完整代码:
var maxa = document.width;
var maxb = document.height;
var up = false;
$(document).ready(function() {
doThis();
});
function doThis() {
var left = parseInt(document.getElementById('circle').style.left);
var top = parseInt(document.getElementById('circle').style.top);
if (top < 50) {
up = false;
}
if (top >= 500 || up) {
up = true;
$("#circle").animate({
top: "-=" + Math.floor(Math.random() * 100 + 1) + "px",
left: "-=" + Math.floor(Math.random() * 100 + 1) + "px"
}, 500, doThis);
}
else {
$("#circle").animate({
top: "+=" + Math.floor(Math.random() * 100 + 1) + "px",
left: "+=" + Math.floor(Math.random() * 100 + 1) + "px"
}, 500, doThis);
}
}
There are several problems with this: 这有几个问题:
To calculate left and top you can also use: 要计算左侧和顶部,您还可以使用:
$("#circle").position().left // or .top (relative to parent object)
$("#circle").offset().left // or .top (relative to window)
Anyway the code seems wrong to me, because you are continuosly calling "animate"; 无论如何,代码对我来说似乎不对,因为你不断地称之为“animate”; you don't let any time for an animation to "run" before calling another animation (and do a nasty function recursion if top>500px).
你不要让动画在调用另一个动画之前“运行”任何时间(并且如果top> 500px则执行令人讨厌的函数递归)。
What you have to do is - wait for the animation to complete, using a time delay or using some event - use a timer to check every n milliseconds if top>500. 你要做的是 - 等待动画完成,使用时间延迟或使用某些事件 - 如果top> 500,使用计时器检查每n毫秒。 If so, STOP the current animation and start a new one in the opposite direction
如果是这样,请停止当前动画并以相反方向开始新动画
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.