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

标签 jquery html 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>

在上面的代码片段中,热点可以放在那个红色背景部分上。如何防止这种情况?请检查下图以便更好地理解。

image

另外on drop如何检查两个热点是否重叠?如果两个热点相互重叠,那么我想更改类,这将改变热点的方向。谢谢

最佳答案

你可以在没有任何插件的情况下实现这一点

$(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 );         
              }
        });    

});

关于jquery - 防止可拖动项目落在特定元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42223287/

相关文章:

javascript - 将光标放在html表格单元格中文本的末尾

jquery ui 自动完成和 json 调用

jquery - 无法动态突出显示背景 - removeClass fadeOut

javascript - WooCommerce 购物车页面 : Remove Item Button move place

javascript - 通过内联 onClick 运行 jQuery 函数并使用函数变量/引用

php - Codeigniter 网站上的 Google Analytics API

html - 使用 css 垂直格式化输入和标签标签

html - 将鼠标悬停在包含多个 div 的容器上? ( flex 盒子)

JQuery UI 自动完成渲染类别与链接

javascript - 使用jquery将H1内容更改为小写