在拖动时设置jQuery可拖动元素的位置

问题描述 投票:1回答:1

在我的网络应用中,有一个可拖动元素。当元素在拖动时达到某个极限时,我需要设置该元素的左侧位置。使用jQuery可拖动小部件,我可以访问元素的位置:

function drag(e, ui) {
 console.log(ui.position.left);
}

假设我的left属性设置为1100px,我需要将其设置为500px,并且不停止拖动。

我具有三个功能:dragStart,drag和gradEnd。目前,我仅得到一个结果:在拖动功能上设置ui.position.left = 500;(使用条件)时,左侧位置设置为500,但是当然,该元素然后停留在500px。原因是每次触发拖动功能时,左侧位置都设置为500。

如果代码仅在行ui.position.left = 500;上运行一次,则left left属性设置为500,但直接重置为1100。

如何一劳永逸地设置left属性?

$("#divId").draggable({
  drag: drag,
})

function drag(e, ui) {
  if (ui.position.top > 50) {
    ui.position.left = 100;
  }
}
#divId {
  height: 70px;
  background-color: white;
  border: 4px solid #000000;
  text-align: center;
  color: black;
  cursor: grab;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="divId">
  Bubble
</div>
javascript jquery css draggable
1个回答
0
投票
我不确定jQuery Draggable如何在后台进行处理,但是即使在设置ui.position.left = 100之后,它也不会在事件中注册,直到停止拖动之后-这就是为什么我选择检查实际的CSS属性定位的元素。



第一个示例,检查left CSS属性:

$("#divId").draggable({ drag: drag }); function drag(e, ui) { const TOP_THRESHOLD = 50; const LEFT_POSITION = 100; if ($(this).css('left') === `${LEFT_POSITION}px`) { // This has to be here. // If this is removed, when you drag, the animation is choppy. // Comment out the line below to see for yourself. ui.position.left = LEFT_POSITION } else if (ui.position.top > TOP_THRESHOLD) { ui.position.left = LEFT_POSITION; } }
#divId { height: 70px; background-color: white; border: 4px solid #000000; text-align: center; color: black; cursor: grab; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="divId">
  Bubble
</div>



第二示例,更多的'基于封闭的功能方法':

不需要您检查CSS ..

$("#divId").draggable({ drag: drag() }); function drag(e, ui) { let TRIGGER = false; const TOP_THRESHOLD = 50; const LEFT_POSITION = 100; return function(e, ui) { if (TRIGGER) { ui.position.left = LEFT_POSITION; } else if (ui.position.top > TOP_THRESHOLD) { TRIGGER = true; ui.position.left = LEFT_POSITION; } } }
#divId { height: 70px; background-color: white; border: 4px solid #000000; text-align: center; color: black; cursor: grab; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="divId">
  Bubble
</div>
© www.soinside.com 2019 - 2024. All rights reserved.