如何使用 setInterval 移动 3 个图片元素
How to move 3 pics elements using setInterval
简而言之,我正在尝试制作这样的东西。
这是我的代码。我只需要使用 setInterval 并且在恢复图片移动动作时它从最后一点开始而不是从第一点开始,
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);
}
首先,您需要定义每个图像的方向。
然后如果一个人到达尽头,改变方向向后
给你基本的工作流程,你可以参考下面的代码。
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.
}
简而言之,我正在尝试制作这样的东西。
这是我的代码。我只需要使用 setInterval 并且在恢复图片移动动作时它从最后一点开始而不是从第一点开始,
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);
}
首先,您需要定义每个图像的方向。 然后如果一个人到达尽头,改变方向向后
给你基本的工作流程,你可以参考下面的代码。
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.
}