繁体   English   中英

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

[英]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);

    }
}​

这有几个问题:

  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则执行令人讨厌的函数递归)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM