每次单击Javascript时移动图像

时间:2017-12-18 09:35:10

标签: javascript

我想在每次点击时移动图像,但使用此代码只能在一次点击时使用。



function moveright() {
  console.log("moveright invoked.");
  var myImg = document.getElementById("image");
  myImg.style.position = "absolute";
  var cLeft = myImg.style.left;
  if (cLeft == 500) {
    console("Maximum reached.");
  } else {
    myImg.style.left = (cLeft + 50) + "px";
  }
}

<img id="image" src="https://i.stack.imgur.com/TiYE3.jpg?s=32&g=1" onclick="moveright()" />
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

  1. 给出初始左侧位置值。您可以添加如下内联样式:@OneToOne @JoinColumn(name = "person_id") private Person person;

  2. 在向其添加50像素之前将左侧值解析为整数:style="left: 0px"

  3. var cLeft = parseInt(myImg.style.left);
    function moveright() {
      var myImg = document.getElementById("image");
      myImg.style.position = "absolute";
      var cLeft = parseInt(myImg.style.left);
      
      if (cLeft == 500) {
        console("Maximum reached.");
      } else {
        myImg.style.left = (cLeft + 50) + "px";
      }  
    }

    或者,您可以跳过<img id="image" src="https://i.stack.imgur.com/TiYE3.jpg?s=32&g=1" onclick="moveright()" style="left: 0px" />样式声明,并使用left获取计算出的样式值。

    window.getComputedStyle
    function moveright() {
      var myImg = document.getElementById("image");
      myImg.style.position = "absolute";
      
      var cLeft = parseInt(window.getComputedStyle(myImg).left);
      
      if (cLeft == 500) {
        console("Maximum reached.");
      } else {
        myImg.style.left = (cLeft + 50) + "px";
      }  
    }

答案 1 :(得分:2)

使用parseInt,因为style.left在px中具有值。如果style.left为空,则将0作为初始值传递。

function moveright() {
  var myImg = document.getElementById("image");
  myImg.style.position = "absolute";
  var cLeft = parseInt(myImg.style.left || 0);

  if (cLeft == 500) {
    alert("Maximum reached.");
  } else {
    myImg.style.left = (cLeft + 50) + "px";
  }
}
<img id="image" src="https://i.stack.imgur.com/TiYE3.jpg?s=32&g=1" onclick="moveright()" />