jquery-ui: immediate draggable on mousedown

2019-07-24 19:48发布

问题:

Working with jQuery-UI, it is possible to make an element draggable by applying .draggable() method on mousedown event. And then drag it on another mouse press (and drag). Is it possible to make element draggable and start dragging immediately by single mouse press (mousedown event).

What happens:

1) press blue rect and try to drag (element not movable);

2) unpress rect and try to drag again (element is movable).

What should happen:

1) press blue rect and drag it --> element is movable.

<!DOCTYPE html>
<html>
    <head>
        <title>draggable() on press</title>
        <meta charset='UTF-8'/>
        <style>#rect{ border: 1px dotted blue; width:100px; height:100px; background-color: lightblue;}</style>
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
        <script src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'></script>
        <script>
            $(document).ready(function(){
                console.log('document is ready');
                $('#rect').mousedown(function(ev){
                    console.log(ev.target.id+' pressed');
                    $(ev.target).draggable();
                    // $(this).draggable(); // Works the same.
                });
            });
        </script>
    </head>
    <body>
        <div id='rect'></div>
    </body>
</html>

回答1:

You need to re-trigger the mousedown event after the widget initialization. You can use .trigger for this:

$('#rect').mousedown(function(ev){
    console.log(ev.target.id+' pressed');
    if ( !$(ev.target).data("ui-draggable") ) {
        $(ev.target).draggable();
        $(ev.target).trigger(ev);
    }
});

Note the draggable data check: you have to only do this ONCE (or you'd get a re-initialised widget and possibly infinite event trigger recursion)

Also, this is the default behaviour if you only just the widget draggable (eg. on document-ready)

$("#rect").draggable();

and not bother with mousedown at all. This is what you should do unless you have very good reason to insist on using the event, which isn't mentioned in the question

Fiddle: https://jsfiddle.net/9ame9ege/