Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

javascript - How to move 3 pics elements using setInterval

In short, I'm trying to make something like this.

enter image description here

Here is my code. I need to use only setInterval and when resuming the pic moving action it starts from the last points not from the first one,

var e = document.querySelector(".img1");
        var img2 = document.querySelector(".img2");
        var img3 = document.querySelector(".img3");



        var x = setInterval(function() {
            var eLeftPos = e.offsetLeft;
            
            e.style.left = eLeftPos + 1 +'px';
            if (parseInt(e.style.left.split("px")[0]) == 400) {
                clearInterval(x);
                backWard();
            }
        }, 5);

        function backWard() {
            var eLeftPos = e.offsetLeft;
            //console.log(eLeftPos);
            setInterval(function() {
                e.style.left = (eLeftPos - 1) + 'px';
            }, 5);
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all, you need to define the direction of each images. And then if one reaches to end, change the direction to backward.

To give you the basic workflow, you can refer to the following code.

const image1 = {
    el: document.querySelector('.image1'),
    direction: 'left'
}
const image2 = {
    el: document.querySelector('.image2'),
    direction: 'down'
}
const image3 = {
    el: document.querySelector('.image3'),
    direction: 'right'
}

let timer = null;

function onStop() {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
}

function onResume() {
    timer = setInterval(() => {
        moveImage();
    }, 5);
}

function moveImage() {
   // here you can check if the images reach to end, then change the direction, otherwise, move the image according to the direction.
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...