jquery-ui: immediate draggable on mousedown

我们两清 提交于 2019-12-11 04:16:07

问题


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/



来源:https://stackoverflow.com/questions/40464357/jquery-ui-immediate-draggable-on-mousedown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!