防止可拖动项目落在特定元素上

时间:2017-02-14 10:11:09

标签: jquery html html5 jquery-ui drag-and-drop

我创建了多个可拖动的热点,但我的问题是在同一个容器中有一个部分;在那一节我不想删除可拖动的元素。请查看下面的代码段。

$(".draggable").draggable({
  containment: ".container",
 
});
.container{
  width:100%;
  position:relative;
  height:300px;
  background:#eaeaea;
}
label{display:inline-block;}
.draggable {
    position: absolute!important;
    min-width: 85px;
    border: none!important;
    background: transparent!important;
    top:0;
    left:0;
    z-index:1;
}
.draggable label:first-child{
  background:blue;
  border:1px solid green;
  width:10px;
  height:10px;
  border-radius:50%;
  float:left;
  margin-top:3px;
  margin-right:10px;
}

.draggable label:last-child {
    overflow: hidden;
    max-width: 100px;
    word-wrap: break-word;
    padding: 5px;
    background: #9afff1;
}

.section {
    position: absolute;
    width: 240px;
    height: 100px;
    background: #dfbaba;
    bottom: 0;
    border: 1px solid #d5a1a1;
}
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="container">
  <div class="draggable">
    <label></label>
    <label>hotspot1</label>
  </div>
  <div class="draggable">
    <label></label>
    <label>hotspot2</label>
  </div>
  <div class="draggable">
    <label></label>
    <label>hotspot3</label>
  </div>
  
  <div class="section">
  </div>
</div>

在上面的代码段中,热点可以放在红色背景部分上。怎么预防?请查看下面的图片以获得更好的理解。

docs

同样关于如何检查两个热点是否重叠?如果两个热点彼此重叠,那么我想改变将改变热点方向的类。感谢

3 个答案:

答案 0 :(得分:3)

你可以通过没有这样的插件来实现这个目标

$(document).ready(function(){

    $(".draggable").draggable({
      containment: ".container" ,             
      stop: function(event,ui ) {                             
        if($(this).draggable('option','revert'))
            $(this).draggable('option','revert', false );           
          },
    });
    //this will prevent any collision
       $(".draggable" ).droppable({
            drop: function( event, ui ) {
            ui.draggable.draggable( 'option', 'revert', true );                     
            }
          });       
       // this will prevent drop on section     
       $( ".section" ).droppable({
              drop: function( event, ui ) {       
            ui.draggable.draggable( 'option', 'revert', true );         
              }
        });    

});

答案 1 :(得分:1)

你应该使用一个额外的插件preventCollision与兄弟

见这里&gt; https://github.com/dsbaars/jq-ui-draggable-collision

或此处&gt; https://sourceforge.net/projects/jquidragcollide/

您的最终代码将是

$(".draggable").draggable({
    containment: ".container",
    obstacle: ".section",
    preventCollision:true


});

在SO&gt;上详细了解此主题Restrict jQuery draggable items from overlapping/colliding with sibling elements

希望它有所帮助。

答案 2 :(得分:0)

你可以尝试停止检查可拖动位置是否超出限制区域,如果是 - 设置恢复为真,并且在开始时再次将其设为假