如何将可拖动元素限制为特定元素

时间:2017-08-16 06:19:25

标签: javascript jquery css jquery-ui

在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

2 个答案:

答案 0 :(得分:1)

您可以移动.container div来换行.dragme,移除position: relative的{​​{1}}并设置以下样式更改。

.container

修改如下。

body {
  position:relative;
}

Here是jsfiddle链接。

<强>编辑:

jquery draggable中有一些选项可以为收容设置.container { position: absolute; height: 362px; } .restricted-field-2 { top: 400px; } x-axis位置,我们需要根据我们的要求进行计算。

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

答案 1 :(得分:0)

&#13;
&#13;
$(".dragme").draggable({
	containment: ".mini"
});
&#13;
.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%;

  
 }
&#13;
<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>
&#13;
&#13;
&#13;

相关问题