如何使用jquery拖放内容

时间:2015-08-17 11:16:10

标签: jquery html css

Here是小提琴。 我试图将hello拖放到div标签中..它很成功。现在我怎样才能将同一个hello放入另一个div标签中。如果掉落目标不止一个,我们怎么能超越目标呢?

2 个答案:

答案 0 :(得分:4)

而不是使用id定位丢弃区域而不是classname。这将照顾一切。以下是变化:



$(document).ready(function()
{
	var data1;
	$(".draggable").bind('drag',function(event)
	{ 
		data1=event.target.id; 
	});
	$(".droppable").on("dragover",function(event){
		event.preventDefault();
		event.stopPropagation();
	});
	$(".droppable").on("dragleave",function(event){
		event.preventDefault();
		event.stopPropagation();
	});
	$(".droppable").on("drop",function(event)
	{
		event.preventDefault();
		var d=document.getElementById(data1).innerHTML;
		event.target.innerHTML=event.target.innerHTML+d;
	});
});

.droppable {width:200px;height:auto;padding:5px;border:2px solid #915C83;min-height: 15px;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="droppable" name="ans"></div>
<div id="div2" class="droppable" name="ans"></div>
<div id="div3" class="droppable" name="ans"></div>
<div id="div4" class="droppable" name="ans"></div>
<div class="draggable" draggable="true" id="drag1">Hello</div>
&#13;
&#13;
&#13;

<强> DEMO

答案 1 :(得分:1)

尝试将事件与类绑定,而不是根据DIV id。这是一个有效的fiddle。我想这就是你想要的!

<强> HTML

<div id="div1" class="droppable" name="ans"></div>
<div id="div2" class="droppable" name="ans"></div>
<div class="draggable" draggable="true" id="drag1">Hello</div>

<强> CSS

#div1 {width:200px;height:auto;padding:5px;border:2px solid #915C83;min-height: 15px;}
#div2 {width:200px;height:auto;padding:5px;border:2px solid #915C83;min-height: 15px;}

<强> JS

$(document).ready(function()
        {
                var data1;
                $(".draggable").bind('drag',function(event)
                    { 
                        data1=event.target.id; 
                    });
                $(".droppable").on("dragover",function(event){
                        event.preventDefault();
                        event.stopPropagation();
                    });
                $(".droppable").on("dragleave",function(event){
                            event.preventDefault();
                        event.stopPropagation();

                    });
                $(".droppable").on("drop",function(event)
                    {
                        event.preventDefault();
                        var d=document.getElementById(data1).innerHTML;
                        event.target.innerHTML=event.target.innerHTML+d;
                    });
        });