调整窗口大小时,可拖动的对象会出现在容器外部

Draggable object goes outside the container when the window is resized

本文关键字:外部 对象 窗口 小时 拖动 调整      更新时间:2023-09-26

我尝试使用drag&JQueryUI 中的拖放功能

我做了这个JSFiddle:

http://jsfiddle.net/96k2ysbf/1/

HTML

<div id="scrollbar-zone" class="w85pc">
  <div id="scrollbar" style=""></div>
</div>

CSS

.w85pc{
  width: 80%;
  margin: 0 auto;
}
#scrollbar-zone{
    border: 1px solid black;
    height: 30px;
}
#scrollbar{
    border: 1px solid red;
    height: 100%;
    width: 10px;
}

Javascript

$("#scrollbar").draggable({
    axis: "x",
    containment: 'parent'
});

它工作得很好,但有时当我调整窗口大小时,可拖动的对象会超出父元素,我想避免这种情况。

解决这个问题最简单的方法是什么?我可以使用resize()事件,但可能有更好的解决方案。

您可以在stop事件中将位置转换为百分比,因此调整滚动条大小时将保持其比例位置。像这样:

$("#scrollbar").draggable({
  axis: "x",
  containment: 'parent',
  stop: function(e, ui) {
    var perc = ui.position.left / ui.helper.parent().width() * 100;
    ui.helper.css('left', perc + '%');
  }
});

http://jsfiddle.net/axmgm2j2/