首页 > 解决方案 > JavaScript 按 X px 按钮移动对象

问题描述

我应该如何通过按钮将对象移动(在这种情况下)10px?在我的代码中,左右按钮不起作用,向上和向左移动图像,但不是 10px,到顶部/左侧边缘。我试过这个:

标签: javascriptbuttonmovemoving-average

解决方案


首先是您的图片没有定位,这意味着它static默认定位,因此您不能使用左、右、上或下样式属性。我已将父母的定位设置为relative和孩子的(img)位置,absolute以便图像的定位将相对于父母(在您的情况下为身体)。

我认为您还想在每次单击按钮时进行增量分配,在这种情况下,您应该首先获取图像的当前位置。您可以使用offsetTopoffsetLeft属性来做到这一点。

body {
  position: relative;
}

img {
  position: absolute;
  left: 200px;
  top: 100px;
}
<body>  

    <img onclick="A()" id='inspo' src="a8.jpg">

    <button id="left" onclick="moveleft()">left</button>
    <button class="right" onclick="moveright()">right</button>
    <button class="down" onclick="movedown()">down</button>
    <button class="up" onclick="moveup()">up</button>

<script type="text/javascript">

function moveleft() {
  const img = document.getElementById('inspo');
  img.style.left = `${img.offsetLeft - 10}px`;
}

function moveright() {
  const img = document.getElementById('inspo');
  img.style.left = `${img.offsetLeft + 10}px`;
}

function moveup() {
  const img = document.getElementById('inspo');
  img.style.top = `${img.offsetTop - 10}px`;
}

function movedown() {
  const img = document.getElementById('inspo');
  img.style.top = `${img.offsetTop + 10}px`;
}


function A() {
  document.getElementById('inspo').style.display = "none";
}
</script>
</body>

编辑:如果你想保持你的原始样式和使用lefttop属性不仅设置值而且获取值,你可以使用下面的代码,注意lefttop属性返回字符串,所以你必须在进行算术之前将结果转换为数字对其进行操作。

<body style="position: relative;">  

    <img style=" position: absolute; left: 100px; top: 100px;" onclick="A()" id='inspo' src="a8.jpg">

    <button id="left" onclick="moveleft()">left</button>
    <button class="right" onclick="moveright()">right</button>
    <button class="down" onclick="movedown()">down</button>
    <button class="up" onclick="moveup()">up</button>

<script type="text/javascript">

function moveleft() {
  const img = document.getElementById('inspo');
  img.style.left = Number(img.style.left.slice(0, -2)) - 10 + 'px';
}

function moveright() {
  const img = document.getElementById('inspo');
  img.style.left = Number(img.style.left.slice(0, -2)) + 10 + 'px';
}

function moveup() {
  const img = document.getElementById('inspo');
  img.style.top = Number(img.style.top.slice(0, -2)) - 10 + 'px';
}

function movedown() {
  const img = document.getElementById('inspo');
  img.style.top = Number(img.style.top.slice(0, -2)) + 10 + 'px';
}


function A() {
  document.getElementById('inspo').style.display = "none";
}
</script>
</body>


推荐阅读