javascript - 为什么这个元素会传播两个不同的距离?
问题描述
我试图以可预测的方式移动一些元素,但是我得到了意想不到的结果。
当你按下“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);
});
解决方案
您只是currentY
在代码的开头阅读,而不是在每次点击时阅读。因此,原始 Y 应用于“向上”,而不是当前值。
推荐阅读
- javascript - 将详细信息传递给模态时 id 未定义
- animation - 容器高度动画从中间开始
- node.js - 在nodejs脚本中从shell命令运行casperjs代码时出错
- php - 如果第二个表不匹配连接条件,laravel 从第一个表中获取结果
- postman - 检索和访问字符串化数据
- wordpress - Woocommerce 登录客户 API 端点
- airflow - apache 气流 - 无法加载 dag bag 来处理故障
- mysql - MySQL 是否支持创建隐藏列?
- python - 在 shell 中将“python -m SimpleSTTPServer”的结果传递给管道
- c# - 与旋转的矩形碰撞