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

问题描述 投票:0回答:2

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

.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);
    }
}
javascript jquery jquery-ui jquery-ui-draggable
2个回答
0
投票

考虑下面的例子。

$(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>

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

更新

调整了包含和功能。现在它接受一个 top 值和一个父 height 值并计算出百分比。


0
投票

如果你想从文档的顶部寻找位置,可以试试这个。

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

如果你想从父文件的顶部寻找位置,就试试这个。 And this if you are looking for position from the top of the parent:

$('.cover').attr('data-offset', Math.ceil(ui.position.top / $parent.height() * 100));
© www.soinside.com 2019 - 2024. All rights reserved.