调整窗口大小时,可拖动对象移出容器 [英] Draggable object goes outside the container when the window is resized

查看:73
本文介绍了调整窗口大小时,可拖动对象移出容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用JQueryUI中的拖放功能创建自定义滚动条

I try to made a custom scrollbar using the drag&drop/draggable function in JQueryUI

我创建了此JSFiddle:

I made this 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'
});

工作正常,但有时当我调整窗口大小时,可拖动对象不在父元素的位置,而我想避免这种情况。

It works fine, but sometimes when I resize the window, the draggable object goes outsite the parent element, and I want to avoid that.

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

What's the easiest way to fix this problem? I could use the resize() event but there's maybe a better solution.

推荐答案

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

You can convert the position to percentage on stop event, so when resizing the scrollbar will keep its proportional position. Like this:

$("#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/

这篇关于调整窗口大小时,可拖动对象移出容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆