I hope the following snippet can be of help, please do not hesitate to ask if there is any doubt.
const img = document.getElementById('img');
const container = img.parentElement;
let left = 0;
let sign = 1;
let ticking = false;
img.style.left = `${left}px`;
img.style.transform = `scaleX(${sign})`;
function translate() {
// YOU CAN CHANGE THE SPEED BY CHANGING THIS.
left += sign * 10;
if (left + img.offsetWidth >= container.clientWidth) {
// CASE: RIGHT LIMIT.
left = container.clientWidth - img.offsetWidth;
sign *= -1;
} else if (left <= 0) {
// CASE: LEFT LIMIT.
left = 0;
sign *= -1;
}
if (ticking) {
return;
}
// THIS WILL RUN THE CALLBACK WHEN THE BROWSER IS READY TO DO A REPAINT. (JUST A PERFORMANCE IMPROVEMENT)
requestAnimationFrame(() => {
img.style.left = `${left}px`;
img.style.transform = `scaleX(${sign})`;
ticking = false;
});
ticking = true;
}
setInterval(translate, 10);
#img {
height: 100px;
width: 100px;
position: absolute;
top: 0;
left: 0;
transition: transform 0.5s linear;
}
<img id='img' src='https://i.imgur.com/kDDFvUp.png' />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…