2017-08-16 98 views
0

在JQuery UI中,我试图将可拖动元素限制为容器中存在的特定元素(.container)。如何将可拖动元素限制为特定元素

即使我试过containment作为数组它正在工作,但在我的情况下,我将不知道.container高度和宽度。请告诉我哪个是正确的做法。

<div class="container"> 
    <div class="restricted-field-1">should be restricted here</div> 
    <div class="dragme">DRAG ME</div> 
    <div class="restricted-field-2">should be restricted here</div> 
</div> 

$(".dragme").draggable({ 
    containment: ".container" 
}); 

JSFIDDLE

+0

你是否试图限制在白色背景区域内的拖动? – kmg

+0

这篇文章可能会有帮助:https://stackoverflow.com/questions/11452185/restrict-jquery-draggable-items-from-overlapping-colliding-with-sibling-elements –

+0

这篇文章可能会有所帮助:https:// stackoverflow .com/questions/11452185/restrict-jquery-draggable-items-from-overlapping-collision -with-sibling-elements –

回答

0

$(".dragme").draggable({ 
 
\t containment: ".mini" 
 
});
.container{ 
 
    position:relative; 
 
    width: 500px; 
 
    height: 400px; 
 
    background: #FFF; 
 
} 
 

 
.dragme{ 
 
    width: 100px; 
 
    cursor: move; 
 
    background: black; 
 
    color:white; 
 
    text-align:center; 
 
} 
 
.restricted-field-1{ 
 
    width:480px; 
 
    background: silver; 
 
    padding:10px; 
 
    user-select:none; 
 
    height: 20px; 
 
} 
 
.restricted-field-2{ 
 
    position:absolute; 
 
    width:480px; 
 
    bottom:0; 
 
    padding:10px; 
 
    background: silver; 
 
    user-select:none; 
 
    height:20px; 
 

 
    
 
} 
 
.mini{ 
 
    position: absolute; 
 
    top: 40px; 
 
    left: 0px; 
 
    bottom: 40px; 
 
    
 
    width: 100%; 
 

 
    
 
}
<div class="container"> 
 
    <div class="restricted-field-1">should be restricted here</div> 
 
    <div class="mini"> 
 
    <div class="dragme">DRAG ME</div> 
 
    </div> 
 
    
 
    <div class="restricted-field-2">should be restricted here</div> 
 
</div> 
 

 
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>

+0

谢谢你的回复,实际上我不必在容器内创建新的元素。 – Kumar

1

可以移动.container div来包裹.dragme,去除.containerposition: relative并设置以下样式的变化。

body { 
    position:relative; 
} 

修改如下。

.container { 
    position: absolute; 
    height: 362px; 
} 
.restricted-field-2 { 
    top: 400px; 
} 

Here是jsfiddle链接。

编辑:

有jQuery中拖动来设置遏制x-axisy-axis位置选择,我们需要计算基于我们的要求。

Here是更新后的js小提琴链接。

+0

是的,这将工作,但实际上我需要做的更改jQuery UI(脚本方)。谢谢 – Kumar

+0

我已经添加了更新的js小提琴链接,并且单独提供了脚本方面的更改。希望有所帮助。 – kmg

+0

是的,这是有效的,但事情是在这里,我不知道容器和限制元素的确切高度和宽度。 谢谢 – Kumar