【问题标题】:Draggable object goes outside the container when the window is resized调整窗口大小时,可拖动对象超出容器
【发布时间】:2016-05-19 15:40:00
【问题描述】:

我尝试使用 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() 事件,但也许有更好的解决方案。

【问题讨论】:

  • 我认为使用 resize() 事件是更简单的解决方案
  • @TimB 感谢您的回答,如果没有人有更好的解决方案,我将使用 resize。

标签: javascript jquery jquery-ui drag-and-drop draggable


【解决方案1】:

您可以在 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/

【讨论】:

  • 我只是在想这个解决方案,然后我看到了你的答案。非常感谢:)
  • 这仅适用于可拖动对象为百分比而非像素的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多