0

嗨,我已经编写了这段代码,它假设在单击对象后每 3000 毫秒移动一次对象,但是有些时间它不起作用,谁能告诉我我做错了什么,我只是在学习 javascript;非常感谢你

function move1() {
    var im1 = document.images[0];
    im1.onclick = function() {
        im1.style.left = parseInt(im1.style.left) + 1 + "px";
    }
}

function move2() {
    var im2 = document.images[1];
    im2.onclick = function() {
        im2.style.left = parseInt(im2.style.left) + 10 + "px";
    }
}

window.onload = function() {
    setInterval(move1, 100);
    setInterval(move2, 3000);
}
4

2 回答 2

2

你反其道而行之。每 3000 毫秒,您可以在单击图像时将图像移动 1 像素。

function move(el, ms, px) {
/* moves the el every ms by px
returns the interval id to clear the movement */
    return setInterval(function() {
        el.style.left = parseInt(el.style.left) + px + "px";
    }, ms);
}
window.onload = function() {
    var im0 = document.images[0];
    var im1 = document.images[1];
    im0.onclick = function() {
        move(im0, 100, 1);
    };
    im1.onclick = function() {
        move(im1, 3000, 10);
    };
}
于 2012-05-21T00:03:38.117 回答
0

您的移动功能会在点击时注册图像,但在用户点击之前实际上不会进行任何移动。你想要的更像是这样的:

function move1() {
    var im1 = document.images[0];
    im1.style.left = parseInt(im1.style.left) + 1 + "px";
}

function move2() {
    var im2 = document.images[1];
    im2.style.left = parseInt(im2.style.left) + 10 + "px";
}

window.onload = function() {
    var im2 = document.images[1];
    im2.onclick = function() {
        setInterval(move2, 3000);
    }

    im1.onclick = function() {
        setInterval(move1, 100);
    }
}
于 2012-05-20T23:56:36.853 回答