【问题标题】:How to restrict draggable element into particular element如何将可拖动元素限制为特定元素
【发布时间】:2017-08-16 06:19:25
【问题描述】:

在 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

【问题讨论】:

标签: javascript jquery css jquery-ui


【解决方案1】:

您可以移动.container div 以包裹.dragme,删除.container 中的position: relative 并设置以下样式更改。

body {
  position:relative;
}

如下修改。

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

Here 是 jsfiddle 链接。

已编辑:

jquery 中有选项可拖动设置x-axisy-axis 位置为容器,我们需要根据我们的要求进行计算。

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

【讨论】:

  • 是的,这会起作用,但实际上我需要在 jquery ui 端(脚本端)进行更改。谢谢
  • 我已经添加了更新的 js fiddle 链接,如您所提到的,仅在脚本方面进行了更改。希望对您有所帮助。
  • 是的,这行得通,但问题就在这里,我不知道容器和受限元素的确切高度和宽度。谢谢
  • 您可以使用 width() 和 height() 计算宽度和高度。小提琴链接在这里:jsfiddle.net/v28r9v3r/12
【解决方案2】:

$(".dragme").draggable({
	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>

【讨论】:

  • 谢谢回复,其实我不用在容器内新建元素。
猜你喜欢
  • 2017-11-01
  • 1970-01-01
  • 2012-11-30
  • 1970-01-01
  • 2022-09-24
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多