JavaScript SetInterval () 在单击后不起作用

JavaScript SetInterval () is not working after clicking

本文关键字:单击 不起作用 SetInterval JavaScript      更新时间:2023-09-26
嗨,我

写了这段代码,它假设在单击对象后每 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);
}

你这样做的方式正好相反。每 3000 毫秒,您可以在单击图像时将图像移动 1px。

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

移动函数在单击时注册图像,但在用户单击之前实际上不会执行任何移动。你想要的更像是这样的:

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