使用可拖动的百分比问题
Problems with percentage using draggable
我正在使用来自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">
代码好像是对的,我想我得计算拖拽的大小,加上或减少总数,什么的,你能帮我吗?
由于您处理的是 .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()));
我正在使用来自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">
代码好像是对的,我想我得计算拖拽的大小,加上或减少总数,什么的,你能帮我吗?
由于您处理的是 .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()));