2017-08-16 97 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