首页 > 解决方案 > 为什么这个元素会传播两个不同的距离?

问题描述

我试图以可预测的方式移动一些元素,但是我得到了意想不到的结果。

当你按下“Down”按钮一次,那么“Up”按钮一旦div不会回到它原来的位置。

当元素明显位于两个不同的位置时,为什么 Y 坐标以 29 开始和结束?

HTML
<button id='btn-up'>Up</button>
<button id='btn-down'>Down</button>
<span class='text'>Y coordinate: <span id="yCoord"></span></span>

<div id="myItem" class="moveItem"></div>


CSS
.text {
  font-family: arial;
  padding-left: 30px;
}

#myItem {
  background-color: red;
  height: 50px;
  width: 50px;
  margin-top: 0px;
}

.moveItem {
  transition: transform .25s ease-in-out;
}


JAVSCRIPT
const pixelDistance = 50;
var currentY = $('#myItem').position().top;

$('#yCoord').text(currentY);

$("#btn-up").on('click', function() {
currentY = currentY - pixelDistance;

$('#myItem').css('transform', 'translateY(' + currentY + 'px)');

$('#yCoord').text(currentY);
});

$("#btn-down").on('click', function() {
currentY = currentY + pixelDistance;

    $('#myItem').css('transform', 'translateY(' + currentY + 'px)');

$('#yCoord').text(currentY);  
});

参考代码:https ://jsfiddle.net/tsf9bz27/

标签: javascriptjqueryhtmlcss

解决方案


您只是currentY在代码的开头阅读,而不是在每次点击时阅读。因此,原始 Y 应用于“向上”,而不是当前值。


推荐阅读