如何使用jQuery Draggable和Droppable实现拖拽功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用jQuery Draggable和Droppable实现拖拽功能相关的知识,希望对你有一定的参考价值。

以下对使用jQuery Draggable和Droppable实现拖拽功能的方法进行了详细的分析介绍。

第一步:左侧元素可以拖
官方给出的实例是直接在要拖动的元素上添加class="ui-widget-content"。最初在所有要拖动的元素都添加了“ui-widget-content”类别。但是测试拖动结果,发现元素只能在它所在的container里面拖动,再往右拖动,div会出现水平或垂直滚动条container设置了overflow:auto。
第二步:将要拖的元素内容复制到draggableDiv上。实现拖动父节点时,其下面的子节点元素也要拖放到右边。如果是拖动的子节点元素,就在右边直接显示子节点元素。父节点和子节点是相对的,因为左侧树形结构的节点可以是无限级的,所以一个元素既可能是子节点元素,也会是父节点元素。通过监听鼠标的mousedown和mouseup事件,来判断用户在拖动元素。

var clickElement = null; $(".threepanels .ptreelist").bind("mousedown",function (event)  
//获取当前mousedown元素的内容
var itemContent = $(this).html(); var draggableDiv = $("#draggableDiv");
$(draggableDiv).css( "display": "block", "height": 0 ); 
//将点击的元素内容复制 
clickElement = $(this).clone(); 
var currentdiv = $(this).offset(); $(draggableDiv).css( "top": currentdiv.top, "left": currentdiv.left ); draggableDiv.trigger(event); 
//取消默认行为 return false; ); 
$("#draggableDiv").mouseup(function (event) $(this).css( "height": "0" ); ); 
//拖动元素时鼠标的位置 
var dragDivLeft = 0; 
var dragDivTop = 0; 
$("#draggableDiv").draggable( containment: "parent", drag: function (event, ui) $("#draggableDiv").css( "width": "260px", "height": "22px" ); 
    $("#draggableDiv").append(clickElement); 
    var closeTop = $(".closeBar").offset().top; 
    dragDivLeft = event.target.offsetLeft; 
    dragDivTop = event.target.offsetTop; , 
    stop: function ()  
        //拖拽结束,将拖拽容器内容清空 
        $("#draggableDiv").html(""); 
        $("#draggableDiv").css("height":"0");  
);

第三步:右边的元素可以放到指定的位置上
需要将元素拖到指定的区域里面,然后释放操作。完成“放”的操作。可以从上图看出,我是将元素的上边左边和下边缘的左边存到一个数组里面。然后在“拖”的过程中,一直记录了拖动的左边,放到右侧时,就可以判断当前元素将要放的位置。具体可以下载代码查看。
完成代码之后的效果图如下:

参考技术A <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery UI Draggable and Droppable Demo</title>
<style type="text/css">
/*reset style*/
body
color: #333;
font-size: 14px;
line-height: 22px;
font-family: "Helvetica","Arial","微软雅黑","宋体";

ul, li, p
padding: 0;
margin: 0;

a
color: #0064a0;
padding: 1px;
text-decoration: none;

a:hover
color: #26a0da;
text-decoration: underline;

#leftpanel
float: left;

.peopletabs li
list-style-type: none;

#maincontainer
width: 800px;
height: 350px;
margin: 0 auto;
border: 2px solid #0069a0;
padding: 10px;

#schoolproperty
height: 250px;
border: 1px solid green;
padding: 10px;
overflow: auto;
width: 350px;
float: left;

#selectedschool
float: right;

#rightlistcontainer
width: 300px;
height: 250px;
overflow: auto;
float: right;
border: 1px solid green;
padding: 10px;

#peopleproperty ul
list-style-type: none;

.ptreelist li
display: block;
width: 200px;

/*拖动的元素最好设置一个宽带和高度*/
#draggableDiv
z-index: 1000;
background-color: Green;
width: 308px;
height: 22px;
position: absolute;
color: #fff;

#middlepanel
width: 100px;
float: left;
margin-top: 120px;

#rightlistcontainer .remove
padding: 5px;
border: 1px solid #b4b4b4;
background: #cdcdcd;

#rightlistcontainer .remove li
width: 240px;
background-color: #cdcdcd;
padding: 0 5px;
background: #fff;
margin-top: 3px;
cursor: move;

#blankarea
margin-top:10px;
height: 50px;
border: 1px dotted red;

jQuery Drag&Drop:拖动一个封闭元素

我正在尝试根据本指南添加拖放功能

https://www.w3schools.com/HTML/html5_draganddrop.asp

我有

CoffeeScript
  $('#topic-list').on 'dragstart', '.topic-draggable', (event) ->
    console.log event
    event.originalEvent.dataTransfer.setData("text", event.target.id)
    console.log event.target
    console.log event.target.id
HTML (ERB)
  <li draggable="true" class="topic-draggable" id="topic_{{{topic_id}}}">
    <a href='<%= topics_path %>/{{{topic_id}}}'>

项目是动态插入的,*_id由数字代替。问题是,当我试图拖动<li>,然后event.target<a>元素,target.id是空白。

Browser console
<a href="/topics/2">
  <i class="fa fa-th"></i>
  <span class="topic-name">Life Span Development</span>
  <i class="fa fa-angle-right"></i>
</a>

如何拖放<li>元素,而不是<a>元素?

我可以使用event.target.parent或一些黑客,但不确定是否正确。我尝试过,但得到了错误Uncaught TypeError: Cannot read property 'parent' of undefined

$('#topic-list').on('dragstart', '.topic-draggable', function(event) {
  console.log(event);
  event.originalEvent.dataTransfer.setData("text", event.target.id);
  console.log(event.target);
  return console.log(event.target.id);
});
ul#topic-list {
        box-sizing: border-box;
        color: white;
        background-color: #20A0D0;
        list-style: none;
        padding: 0;
        margin: 0;
}
        li {
          list-style: none;
}
          li:nth-child(even) {
            background-color: #3DB1E7;
          }

          a {
            padding: 20px 20px;
            display: flex;
            font-size: 1.4em;
            text-decoration: none;
            color: white;
            justify-content: space-between;
          }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

<ul id="topic-list" style="display: block;">
  <li draggable="true" class="topic-draggable" id="topic_1">
    <a href="/topics/1">
      <i draggable="true" class="fa fa-th topic-draggable"></i>
      <span class="topic-name">Introduction to A&amp;P</span>
      <i class="fa fa-angle-right"></i>
    </a>
  </li>

  <li draggable="true" class="topic-draggable" id="topic_2">
    <a href="/topics/2">
      <i draggable="true" class="fa fa-th topic-draggable"></i>
      <span class="topic-name">Life Span Development</span>
      <i class="fa fa-angle-right"></i>
    </a>
  </li>

  <li draggable="true" class="topic-draggable" id="topic_3">
    <a href="/topics/3">
      <i draggable="true" class="fa fa-th topic-draggable"></i>
      <span class="topic-name">Medical Terminology</span>
      <i class="fa fa-angle-right"></i>
    </a>
  </li>

</ul>

我实际上无法创建一个例子,因为StackOverflow的代码编辑器给出了错误DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.

答案

好吧,我终于惊慌失措了。

CoffeeScript
  topicDrag = false
  currentTarget = null
  $('#topic-list').on 'dragstart', '.topic-draggable', (event) ->
    li = $(event.target).parent().parent()
    event.originalEvent.dataTransfer.setData("text", li.attr('id'))
    li.css('border', '1px dashed red').css('opacity', '0.3')
    topicDrag = true

  $('#topic-list').on 'dragover', 'li', (event) ->
    event.preventDefault() if topicDrag # allow drop, but only for our topics, not random links

  $('#topic-list').on 'dragenter', 'li', (event) ->
    return unless topicDrag
    # browser will call dragleave after dragenter when moving from one <li> to another, turning off the border. fix order.
    currentTarget = event.target # save only the very last target
    setTimeout ->
      # console.log 'dragenter '+currentTarget.nodeName
      $(currentTarget).parentsUntil('#topic-list', 'li').css('border', '2px dashed yellow')
    , 100

  $('#topic-list').on 'dragleave', 'li', (event) ->
    # console.log 'dragleave '+event.target.nodeName
    # when jumping from li > a > span to another, browser calls events in wrong order. clear all.
    $('#topic-list').children().css('border', 'initial')

  $('#topic-list').on 'drop', 'li', (event) ->
    event.preventDefault()
    data = event.originalEvent.dataTransfer.getData("text")
    # console.log data
    source = $('#'+data)
    # the browser allows dropping on child elements of <li> for some reason
    $(event.target).parentsUntil('#topic-list', 'li').before( source ).css('border', 'initial')
    source.css('opacity', 'initial').css('border', 'initial')
    topicDrag = false
HTML-ERB
  <li id="topic_{{{topic_id}}}">
    <a href='<%= topics_path %>/{{{topic_id}}}'>
      <%= fa_icon 'th', draggable: true, class: 'topic-draggable' %>
      <span class='topic-name'>{{{topic_name}}}</span>
      <%= fa_icon "angle-right" %>
    </a>
  </li>

以上是关于如何使用jQuery Draggable和Droppable实现拖拽功能的主要内容,如果未能解决你的问题,请参考以下文章

如何在一个页面中动态放置多个Droppable来接受不同的Draggable

制作一个包含img draggable的div

前端开发谈谈H5的原生元素拖拽(drap& drop)事件

draggable jquery get start parent()元素

html新特性——拖拽(drag和drop)

jQuery draggable : 只能在一个 droppable 上拖动