jquery, перетаскиваемый с добавленной функциональностью нажатия клавиш - PullRequest
1 голос
/ 14 мая 2011

Я хочу реализовать «перетаскиваемый» элемент управления из jQueryUI.
Когда пользователь перетаскивает значок мышью, он может куда-то уронить этот значок (например, на изображение).

Я также хочу иметь расширенные функциональные возможности - когда пользователь нажимает клавишу, к мыши прикрепляется значок, и щелчком мыши значок можно отбрасывать (в тех же местах, что и перетаскиваемый значок).

Аналогичная функциональность была реализована в игре Silverlight Robozzle: http://robozzle.com/

Очевидно, я буду использовать это: http://code.google.com/p/js-hotkeys/,, но мой вопрос:
Как программно создать и прикрепить перетаскиваемый объект jQuery к курсору мыши?
То есть фактически не перетаскивая его мышью.

1 Ответ

1 голос
/ 15 мая 2011

Для большей части этой функциональности вам даже не нужен jQuery UI или какие-либо плагины. Посмотрите мое демо здесь: http://jsfiddle.net/cJzeP/2/

Если вы хотите продолжать перетаскивать значки вместо моего решения по щелчку, вы можете легко объединить их. См. Комментарии в коде для более подробного объяснения, если это необходимо.

HTML:

<div id="iconA" class="icon">A</div>
<div id="iconB" class="icon">B</div>
<div id="iconC" class="icon">C</div>

<div class="drop">Drop stuff here: </div>

CSS:

.icon { display:inline-block; margin:5px; background-color:whitesmoke; border:1px solid silver; width:20px; height:20px; text-align:center; }

.drop { padding:20px; border:1px solid blue; }

Javascript:

// The dragged element wrapped in a jQuery object or null
var $dragHelper = null;

// The last known mouse position The keypress event doesn't
// send the position through, we need this for the hotkey
// activation so we can show the icon next to the cursor.
var lastX = 0;
var lastY = 0;

// Start dragging the element with the passed id
function StartDrag(id){
    // Clone the element, make it absolutely positioned and
    // append it to the body.
    $dragHelper = $('#' + id).clone().css('position', 'absolute').appendTo('body');

    // Fire the dragging event to update the helper's position
    Dragging();

    // If the user clicks anything outside the drop area,
    // stop dragging.
    $(document).click(StopDrag);
}

function StopDrag(){
    // Remove the helper from the DOM and clear the variable.
    $dragHelper.remove();
    $dragHelper = null;

    // Unbind the document click event which is now useless.
    $(document).unbind('click', StopDrag);
}

// Fires on mousemove and updates element position
function Dragging(e){
    // Only update last known mouse position if an event object
    // was passed through (mousemove event).
    if(e){
        lastX = e.pageX;
        lastY = e.pageY;
    }

    // If an element is being dragged, update the helper's position.
    if($dragHelper)
        $dragHelper.css({ top: lastY, left: lastX });
}

// What happens when a key is pressed?
$(document).keypress(function(e){
    var ch = String.fromCharCode(e.which).toLowerCase();
    switch(ch){
        case 'a':
            StartDrag('iconA');
            break;
        case 'b':
            StartDrag('iconB');
            break;
        case 'c':
            StartDrag('iconC');
            break;
    }
});

// Bind the document mousemove event as we need to update our last
// known mouse coordinates constantly for the keypress event.
$(document).mousemove(Dragging);

// Make the icons clickable
$('.icon').click(function(e){
    // Start dragging this icon if it's clicked
    StartDrag($(this).attr('id'));

    // We need to stop event bubbling as it would straight away
    // trigger a click on the document, which stops dragging.
    e.stopPropagation();
});

// Make our drop area clickable
$('.drop').click(function(){
    // Only do something is an element is being dragged
    if($dragHelper){
        // Stuff to do when an element is dropped goes here.

        // For the sake of this example, we just clone the helper
        // and append it to our drop container.
        $dragHelper.clone().css({
            position: 'relative',
            top: '0px',
            left: '0px'
        }).appendTo(this);

        // Stop dragging if an element was successfully dropped.
        StopDrag();
    }
});
...