为什么这个非常简单的javascript/jquery代码无法正常工作

Why this very simple javascript/jquery code won't work correctly

本文关键字:常工作 工作 代码 jquery 非常 简单 javascript 为什么      更新时间:2023-09-26

我有一个非常简单的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();
}​

在再次调用函数之前需要设置超时'' 将函数作为回调传递

现场演示

完整代码:

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);
    }
}​

这有几个问题:

  1. 您无法从 DOM 元素的"style"属性读取来自 CSS 的样式信息。无论如何,你都在使用jQuery;它可以为您提供样式信息。
  2. 对"动画"的调用不会同步完成。你可以传递"dothis"作为第三个参数,jQuery将在动画完成后调用你的函数。

这是一个工作版本。

要计算左侧和顶部,您还可以使用:

$("#circle").position().left // or .top (relative to parent object)
$("#circle").offset().left // or .top (relative to window)

无论如何,代码对我来说似乎是错误的,因为您一直在调用"animate";在调用另一个动画之前,您不会让任何时间让动画"运行"(如果top>500px,则执行令人讨厌的函数递归)。

你要做的是- 等待动画完成,使用时间延迟或使用某些事件- 使用计时器每n毫秒检查一次,如果top>500。如果是这样,请停止当前动画并在相反方向上启动一个新动画