我的目标是一个小游戏,语句可以拖放到两个不同的区域。一个是正确的,一个不是。根据我想改变 backgroundcolor 。我正在努力确定条件。
列表框1中的项目1 - 框2中的绿色/列表项目1 - 红色,反之亦然
示例:http://codepen.io/TheRed/pen/uGKom 非常感谢!
HTML
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">Box 1</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">Box 2</div>
<p id="drag1" draggable="true" ondragstart="drag(event)" name="green">Statement 1</p>
<p id="drag2" draggable="true" ondragstart="drag(event)" name="red">Statement 2</p>
CSS
#div1 {height:50px; width:400px; border:2px solid black;}
#div2 {height:50px; width:400px; border:2px solid black; margin-top: 20px }
p {font-weight:bold; width:200px;}
和JS:
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
if(document.getElementById(data).id == 'drag1'){
document.getElementById('div1').style.background = 'green';
}
else if(document.getElementById(data).id == 'drag2'){
document.getElementById('div2').style.background = 'red';
}
}
答案 0 :(得分:0)
尝试这种方式,我使用了droppable和draggable。
每个draggable和droppable元素都有一个data-target
,它应匹配以获得绿色背景
<强> DEMO 强>
$(function() {
$( ".draggable" ).draggable();
$( ".droppable" ).droppable({
drop: function( event, ui ) {
$('.droppable[data-target="' + ui.draggable.attr('data-target') + '"]').removeClass('backgroundRed').removeClass('backgroundGreen');
if (ui.draggable.attr("data-target")==$(this).attr("data-target")){
$( this ).removeClass("backgroundRed").addClass( "backgroundGreen" );
}
else{
$( this ).removeClass("backgroundGreen").addClass( "backgroundRed" );
}
}});
});
CSS
.backgroundGreen{
background:green!important;
}
.backgroundRed{
background:red!important;
}
.backgroundGray{
background:#cdcdcd!important;;
}
HTML
<div id="draggable1" class="ui-widget-content draggable" data-target="1">
<p>Drag me to my target</p>
</div>
<div id="droppable1" class="ui-widget-header droppable" data-target="1">
<p>Drop here</p>
</div>
<div id="draggable2" class="ui-widget-content draggable" data-target="2">
<p>Drag me to my target</p>
</div>
<div id="droppable2" class="ui-widget-header droppable" data-target="2">
<p>Drop here</p>
</div>