javascript - 如何使用 setInterval 移动 3 个图片元素
问题描述
简而言之,我正在尝试制作这样的东西。
这是我的代码。我只需要使用 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.
}
推荐阅读
- node.js - 如何重定向到 node.js 中同一文件夹中的不同 ejs 文件
- python - 如何将 for 循环的输出转换为 Python 中的单个字符串列表?
- java - Java:对象池和哈希集
- reactjs - 如何使用 Material-ui 和 GraphQL 制作动态标签
- typescript - 编译为 umd 时如何在打字稿中修复车把“找不到模块”
- reactjs - 我的组件正在创建 TypeError: Cannot read property 'click' of null
- java - 滚动时列表视图中的开关状态不稳定
- php - 如何使用 GET 方法选择正确的表格来显示 ChartJS 图形?
- html - CSS grid-column-start 根据屏幕大小制作全宽
- c++ - C++ // 尝试重写工作代码以包含我的函数