Accepting the animation

前端 未结 2 795
后悔当初
后悔当初 2021-02-07 22:10

EDIT**

In my word game there is a grid with 3 letter words.

The aim of the game is to spell the words by clicking on the corresponding letters

2条回答
  •  无人及你
    2021-02-07 22:20

    Why not using a draggable/droppable element with an accept/revert setting, since you are using jQuery UI already?

    Here is a theoretical way to accomplish an accept/revert drag & drop:

    First you need to set your draggable to revert if it is not accepted:

    $(".drag").draggable({ revert: 'invalid' });
    

    Then of course you need to define what is valid in your droppable :

    $(".drop").droppable({ accept: '.drag' });​
    

    Either you try using a selector to filter the right answers, by setting a class for each letter (.addClass("b");) and later change dynamically this selector with .droppable("option","accept",".b"). Or use the magic powder included in jQuery UI. You can insert a function as a value for "accept", it's returned value will define what you accept as a valid element: $(".drop").droppable( { accept: function() { // add a conditon here to return true or false } });​

    Edit

    To do the same with your click event :

    $('.drag').on('click', function(e)
    {
        e.preventDefault();
    
        var target     = $('.drop-box.spellword:not(.occupied):first');
        var targetPos  = target.position();
        var currentPos = $(this).offset();
        var b = $(this);
    
        if(target.length)
        {
            // compare clicked letter with expected letter
            if(b.attr("data-letter") == target.attr("data-letter"))
            {
                b.remove().appendTo('table').css({
                'position' : 'absolute',
                'top' : currentPos.top,
                'left': currentPos.left
                });
    
                b.animate({
                   top  : targetPos.top,
                    left : targetPos.left
                }, 'slow', function() {
                    b.remove().css({ top: 0, left: 0 }).appendTo(target);
                    target.addClass('occupied');
                });
            }
        }
    });
    

提交回复
热议问题