调整 window 大小时,可拖动对象超出容器
Draggable object goes outside the container when the window is resized
我尝试使用 JQueryUI 中的 drag&drop/draggable 函数制作自定义滚动条
我制作了这个 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'
});
它工作正常,但有时当我调整 window 大小时,可拖动对象超出父元素,我想避免这种情况。
解决此问题最简单的方法是什么?我可以使用 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 + '%');
}
});
我尝试使用 JQueryUI 中的 drag&drop/draggable 函数制作自定义滚动条
我制作了这个 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'
});
它工作正常,但有时当我调整 window 大小时,可拖动对象超出父元素,我想避免这种情况。
解决此问题最简单的方法是什么?我可以使用 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 + '%');
}
});