jQuery-ui-draggable 将像素值转换为百分比



设置时如何将ui.position.top值转换为百分比data-offset属性。

.draggable({
scroll: false,
axis: "y",
drag: function (event, ui) {
y1 = $parent.height();//height of the parent elem
y2 = $elem.height(); //height of the elem that is being dragged
if (ui.position.top >= 0) {
ui.position.top = 0;
} else if (ui.position.top <= (y1 - y2)) {
ui.position.top = y1 - y2;
}
},
stop: function(event, ui) {
//convert value to percentage and set prop.
$('.cover').attr('data-offset', ui.offset.top);
}
}

请考虑以下示例。

$(function() {
function topToPerc(t, p, round) {
var result = 0;
if (round == undefined) {
result = parseFloat(((t / p) * 100).toFixed(2));
} else {
result = Math.round((t / p) * 100);
}
return result;
}
$(".box").each(function(i, el) {
if (i != 2) {
$("p", el).html(topToPerc($(el).position().top, $(".page").height()) + "%");
} else {
$("p", el).html(topToPerc($(el).position().top, $(".page").height(), true) + "%");
}
});
$(".box").draggable({
axis: "y",
containment: [0, 0, 350, 200],
drag: function(e, ui) {
if ($(this).index() != 2) {
$("p", this).html(topToPerc(ui.position.top, $(".page").height()) + "%");
} else {
$("p", this).html(topToPerc(ui.position.top, $(".page").height(), true) + "%");
}
}
});
});
body,
.page {
margin: 0;
padding: 0;
}
.page {
position: relative;
height: 200px;
}
.box {
width: 150px;
height: 2em;
position: absolute;
}
.box p {
margin: 3px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="page">
<div class="box ui-widget-content" style="top: 10px; left: 8px; background: #fcc;">
<p></p>
</div>
<div class="box ui-widget-content" style="top: 175px; left: 160px; background: #cfc;">
<p></p>
</div>
<div class="box ui-widget-content" style="top: 200px; left: 312px; background: #ccf;">
<p></p>
</div>
</div>

您的帖子没有包含完整的示例。所以我不确定你想寻找什么。如您所见,这显示了基于高度的百分比。您也可以考虑使用修改后的滑块:https://jqueryui.com/slider/#slider-vertical

更新

调整了遏制和功能。现在,它接受top值和父height值并计算百分比。

如果您正在寻找文档顶部的位置,请尝试以下操作:

$('.cover').attr('data-offset', Math.ceil(ui.offset.top / $parent.height() * 100));

如果您正在寻找父级顶部的位置:

$('.cover').attr('data-offset', Math.ceil(ui.position.top / $parent.height() * 100));

最新更新