Mi pregunta es: ¿cómo evito que la imagen se mueva hacia la izquierda cuando alcanza el ancho máximo de pantalla del usuario? Probé el siguiente método usando JavaScript pero no funciona. Además, cuando la imagen alcanza el ancho máximo del usuario, debe cambiar la dirección y volver a donde estaba antes.
<img src="plane.jpg" width="100px" height="100px" id="plane"> <script type="text/javascript"> var height = document.documentElement.clientHeight; var width = document.documentElement.clientWidth; var plane = document.getElementById("plane"); var leftpos = 0; setInterval(function(){ if (leftpos != width) { leftpos += 10; plane.style.marginLeft = leftpos + 'px' }else { // change the direction } }, 50) // run code every 50 milliseconds ; </script>Aprecie su tiempo y Cuídese.
Puede verificar si marginLeft y el width de la imagen más 10 es menor que window.innerWidth .
var height = document.documentElement.clientHeight; var width = window.innerWidth; var plane = document.getElementById("plane"); var leftpos = 0; var right = true; var id = setInterval(function() { if (right && leftpos + plane.width + 10 <= width) { leftpos += 10; } else { right = false; leftpos -= 10; if (leftpos <= 0) clearInterval(id); } plane.style.marginLeft = leftpos + 'px'; }, 50); <img src="plane.jpg" width="100px" height="100px" id="plane">