我正在使用Jquery UI中的draggable来做拖动效果,困难在于计算从0到100的拖动在条中的位置。下面是我所做的:
$('.drag').draggable({
axis: 'x',
containment: 'parent',
drag: function() {
var largura = $('.bar').width();
var posicaoX = $(this).position().left;
posicaoX = (posicaoX*100)/largura;
var l = (100 * parseFloat($(this).position().left / parseFloat($(this).parent().width())));
$('#show').val(l);
}
});.bar{
width: 150px;
height: 5px;
background: #000000;
position: relative;
margin-top: 20px;
margin-bottom: 20px;
}
.drag{
width: 20px;
height: 20px;
background: #d18f4f;
position: absolute;
top: -7px;
left: 0px;
cursor: pointer;
}<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div class="bar">
<div class="drag"></div>
</div>
<input type="text" value="0" id="show">
代码似乎是正确的,我想我必须计算拖拽的大小,然后添加或减少总数,或者其他什么,你能帮我吗?
发布于 2019-05-03 23:46:23
由于要处理.drag元素的左边缘,因此必须考虑该元素的宽度,因为draggable不会让右侧滑过.bar的末尾
所以很简单:
var l = (100 * parseFloat($(this).position().left / parseFloat($(this).parent().width()-20)));
或
var l = (100 * parseFloat($(this).position().left / parseFloat($(this).parent().width() - $(this).width()));
https://stackoverflow.com/questions/55973004
复制相似问题