我有一个嵌套的可拖动元素。 <强> My Fiddle is here.
我想要的是设置可拖动子元素的上限,使子元素永远不会与父标题重叠。
我将它包含在父标题中,但无法设置顶部位置,因此它不会拖到父标题。
_________________________
|_Parent__________________| <------- Don't overlap the containing parent heading
| |
| ___________ |
| |_Child_____| |
| | | |
| | | |
| | | |
| |___________| |
|_________________________|
HTML:
<div id="wrapper">
<div id="Parent">
<h4 class="ui-widget-header">Parent</h4>
<div id="Child">
<h4 class="ui-widget-header">Child</h4>
</div>
</div>
</div>
CSS:
#wrapper {
width: 800px;
height: 800px;
background: Yellow;
}
#Parent {
width: 250px;
height: 250px;
background: grey;
top: 100px;
left: 100px;
}
#Child {
width: 100px;
height: 100px;
background: white;
top: 0px;
left: 50px;
}
脚本:
$(function () {
$('#Parent').draggable({
cursor: 'move',
containment: 'parent'
});
$("#Child").draggable({
cursor: 'move',
containment: 'parent'
});
});
最佳答案
尝试使用以下代码在拖动时设置限制。只需尝试通过在 event drag 上调用该方法来重置可拖动子项的 top position
在 $("#Child").draggable({})
中。对于您当前的场景 top: -20
是合适的,但如果您的父级可拖动标题更大,则相应地设置值。
drag: function (event, ui) {
var divPos = ui.position.top;
if (divPos < -20) {
ui.position.top = -20;
}
}
下面给出了您的代码的嵌入片段。
$(function() {
$('#Parent').draggable({
cursor: 'move',
containment: 'parent'
});
$("#Child").draggable({
cursor: 'move',
containment: 'parent',
drag: function(event, ui) {
var divPos = ui.position.top;
if (divPos < -20) {
ui.position.top = -20;
}
}
});
});
#wrapper {
width: 800px;
height: 800px;
background: Yellow;
}
#Parent {
width: 250px;
height: 250px;
background: grey;
top: 100px;
left: 100px;
}
#Child {
width: 100px;
height: 100px;
background: white;
top: 0px;
left: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<div id="wrapper">
<div id="Parent">
<h4 class="ui-widget-header">Parent</h4>
<div id="Child">
<h4 class="ui-widget-header">Child</h4>
</div>
</div>
</div>
关于javascript - 将顶部位置设置为可拖动父项内的可拖动子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28880742/