简体   繁体   中英

jQuery Draggable, Droppable query

I'm looking to build a web application similar to the game of the Fox, Chicken and Oats. The riddle where you need to get each across a river but can't leave some items together. Fox, Chicken, Oats

So I am trying to drag for example the chicken first (pink square to blue square), then drag the fox (red-square) to blue and take back the chicken (pink) drop the pink square and bring the oats (yellow) over to the blue. So I need an alert if for example the red/pink end up alone on the same side and same with the pink/yellow.

Here is my code so far:

    <body>
<div id="red-square">Fox</div>
<div id="blue-square">Other Side</div>
<div id="yellow-square">Oats</div>
<div id="pink-square">Chicken</div>

<script type="text/javascript">

    $("#red-square").draggable();
    $("#pink-circle").draggable();
    $("#yellow-square").draggable();
    $("#blue-square").droppable({
        drop: function( event, ui ) {
        alert("No");

    }

    });     

</script>

</body>

For draggable, you want to revert if the drop returns a false value. For example:

 $(function() { function findFox() { var $items = $(".house").find(".piece"); var fox = false; if ($items) { $items.each(function(i, el) { if ($(el).hasClass("fox")) { console.log("Fox Found."); fox = true; } }); } return fox; } $(".piece").draggable({ revert: true }); $("#blue-square").droppable({ accept: ".piece", drop: function(event, ui) { var $drag = ui.draggable; var fox = false; if ($drag.hasClass("chicken")) { fox = findFox(); } if (fox) { return false; } else { $drag.attr("style", "") .appendTo($(this)); } } }); }); 
 .piece { display: inline-block; margin: 10px; padding: 1.5em 1em; text-align: center; } .house { position: relative; padding: 1em; height: 3em; } .house .title { position: absolute; top: 10px; left: 10px; } .red { border: 1px solid red; background: rgba(255, 0, 0, .35); } .blue { border: 1px solid blue; background: rgba(0, 0, 255, .35); } .yellow { border: 1px solid yellow; background: rgba(255, 255, 0, .35); } .pink { border: 1px solid pink; background: rgba(170, 0, 20, .35); } 
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <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 id="red-square" class="red fox piece">Fox</div> <div id="blue-square" class="blue house"> <span class="title">Other Side</span> </div> <div id="yellow-square" class="yellow oat piece">Oats</div> <div id="pink-square" class="pink chicken piece">Chicken</div> 

There is more to do, but this can help explain the basics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM