【问题标题】:Javascript - random images errorJavascript - 随机图像错误
【发布时间】:2013-08-09 05:10:34
【问题描述】:

我有以下问题我有 21 张小图片,我希望它们在定义的时间间隔内随机放置在窗口中。

我有以下代码,我知道是什么导致了问题,但我无法解决。

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

addLoadEvent(Prep6);
addLoadEvent(Prep7);

function Prep6() {

    window_Height = window.innerHeight;
    window_Width = window.innerWidth;

    image_Element = document.getElementById("loader06");
    image_Height = image_Element.clientHeight;
    image_Width = image_Element.clientWidth;

    availSpace_V = window_Height - image_Height;
    availSpace_H = window_Width - image_Width;

    moveImage7();

    var changeInterval = 300;
    setInterval(moveImage7, changeInterval);
}

function moveImage6() {
    var randNum_V = Math.round(Math.random() * availSpace_V);
    var randNum_H = Math.round(Math.random() * availSpace_H);

    image_Element.style.top = randNum_V + "px";
    image_Element.style.left = randNum_H + "px";
}

function Prep7() {

    window_Height = window.innerHeight;
    window_Width = window.innerWidth;

    image_Element = document.getElementById("loader07");
    image_Height = image_Element.clientHeight;
    image_Width = image_Element.clientWidth;

    availSpace_V = window_Height7 - image_Height;
    availSpace_H = window_Width - image_Width;

    moveImage7();

    var changeInterval = 300;
    setInterval(moveImage7, changeInterval);
}

function moveImage7() {
    var randNum_V = Math.round(Math.random() * availSpace_V);
    var randNum_H = Math.round(Math.random() * availSpace_H);

    image_Element.style.top = randNum_V + "px";
    image_Element.style.left = randNum_H + "px";
}

问题是:

moveImage7();
function moveImage6()

我该如何解决?

【问题讨论】:

  • 那么,有什么问题呢?出了什么问题?

标签: javascript


【解决方案1】:

我相信您遇到了一些范围问题。换句话说,您的 moveImage6() 和 moveImage7() 函数中使用的变量不可见,因为它们是其他函数的本地变量。要解决此问题,您必须将这些变量传递给您的 moveImage 函数。您的 moveImage 函数通过 setInterval 函数定期调用,因此传递参数如下:

setInterval(function(){
    moveImage6(availSpace_V, availSpace_H, image_Element);
 }, changeInterval);

这还需要您更新 moveImage6() 和 moveImage7() 函数以接受这些参数。

Passing parameters with setInterval

jsfiddle: simplified in action

希望这会有所帮助!

PS:您可能想将 prep7() 中的 window_Height7 更改为 window_Height

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2013-11-10
    • 1970-01-01
    • 2017-04-23
    • 2021-01-18
    • 2017-07-14
    相关资源
    最近更新 更多