[英]Why this very simple javascript/jquery code won't work correctly
我有一个非常简单的JavaScript / jquery代码,它不能正常工作。 问题似乎是在运行循环时似乎没有计算id为'circle'的div的定位。 只需知道问题发生的原因以及是否有任何修复方法。
这里是链接http://jsfiddle.net/TDRyS/基本上我要做的是尝试在距离顶部500px的距离时将球移动。
编码:
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();
}
在再次调用函数之前需要setTimeout \\将函数作为回调函数传递
完整代码:
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);
}
}
这有几个问题:
这是一个工作版本。
要计算左侧和顶部,您还可以使用:
$("#circle").position().left // or .top (relative to parent object)
$("#circle").offset().left // or .top (relative to window)
无论如何,代码对我来说似乎不对,因为你不断地称之为“animate”; 你不要让动画在调用另一个动画之前“运行”任何时间(并且如果top> 500px则执行令人讨厌的函数递归)。
你要做的是 - 等待动画完成,使用时间延迟或使用某些事件 - 如果top> 500,使用计时器检查每n毫秒。 如果是这样,请停止当前动画并以相反方向开始新动画
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.