首页 > 解决方案 > 达到屏幕的最大宽度后图像没有停止

问题描述

我的问题是:当图像达到用户的最大屏幕宽度时,如何阻止图像向左移动?我使用 JavaScript 尝试了以下方法,但它不起作用。此外,当图像达到用户的最大宽度时,它应该改变方向并返回到之前的位置。

<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>

珍惜你的时间并保重。

标签: javascript

解决方案


您可以检查图像加 10 的marginLeftwidth是否小于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">


推荐阅读