javascript jQuery 如何在鼠标仍然按下时触发拖动事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8759884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:30:02  来源:igfitidea点击:

jQuery How to fire the drag event while mouse is still down

javascriptjqueryjquery-uidom

提问by Ally

Ok I've been playing around with this for hours now and still no dice. I'm creating an interface allowing you to drag and drop an icon(a div with an image inside). I'm using the jQuery UI scriptsfor they're tried and tested div dragging functionality.

好吧,我已经玩了几个小时了,但仍然没有骰子。我正在创建一个界面,允许您拖放图标(内部带有图像的 div)。我正在使用jQuery UI 脚本,因为它们已经过尝试和测试 div 拖动功能。

My problem is you can not drag a div outside it's parent div. To get around this I'm creating a dragable div, appended to the document body, on demand when a user fires a mousedown event. But I can't figure out how to fire off the drag event needed so the user can immediately start dragging this newly created div around.

我的问题是你不能将一个 div 拖到它的父 div 之外。为了解决这个问题,我在用户触发 mousedown 事件时按需创建了一个可拖动的 div,附加到文档正文。但我不知道如何触发所需的拖动事件,以便用户可以立即开始拖动这个新创建的 div。

In short I need to; mouse down -> call function to create draggable div -> drag the div around while the mouse is still down.

简而言之,我需要;鼠标按下 -> 调用函数来创建可拖动的 div -> 在鼠标仍然按下时拖动 div。

I'm sure it's something simple. Any help would be much appreciated.

我确定这很简单。任何帮助将非常感激。

Here is an example of my problem, all it needs to run are the jQuery UI scripts which can be found at the link above.

这是我的问题的一个例子,它需要运行的只是 jQuery UI 脚本,可以在上面的链接中找到。

<html>
<head>
    <script src="../../jquery-1.6.2.js"></script>
    <script src="../../ui/jquery.ui.core.js"></script>
    <script src="../../ui/jquery.ui.widget.js"></script>
    <script src="../../ui/jquery.ui.mouse.js"></script>
    <script src="../../ui/jquery.ui.draggable.js"></script>
    <style>
    #inactive_dragable { width: 50px; height: 50px; padding: 0.5em; background-color: green; }
    .test_drag { width: 50px; height: 50px; padding: 0.5em; background-color: red; position: absolute; }
    </style>
    <script>

    function createDraggableDiv(e){     
        if (!e) var e = window.event;   
        jQuery('<div/>', {
            id: 'tester',
        }).appendTo('#page_wrap');      
        var isIE = document.all ? true : false;
        var _x,_y;
        if (!isIE) {
            _x = e.pageX;
            _y = e.pageY;
        }
        if (isIE) {
            _x = e.clientX + document.body.scrollLeft;
            _y = e.clientY + document.body.scrollTop;
        }
        var boundry = $('#page_wrap').offset();
        $('#tester').addClass('test_drag');
        $('#tester').html("New div to drag");
        $('#tester').css("top", _y + "px");
        $('#tester').css("left", _x + "px");
        $('#tester').draggable();       
        // Now how do I make the new div immediately start dragging?
        // ...
    }
    </script>
</head>
<body>
<div id="page_wrap">
<div class="demo" style="width: 300px; height: 200px; background-color: blue; overflow-y: auto; overflow-x: hidden;">
<div onmousedown="createDraggableDiv(event);" id="inactive_dragable" class="ui-widget-content">
    <p>Drag me around</p>
</div>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</div>
</div>
</body>
</html>

When you click on the div I want to be able to create a new div and drag that around instantly.

当您单击 div 时,我希望能够创建一个新 div 并立即拖动它。

采纳答案by Kyle

Final edit. Here is the functionality you want. I had to modify your code a lot but this does what you want it to do. You need to pass the mousedown event you are firing into a trigger on the added div. Here is the new jsfiddle

最终编辑。这是您想要的功能。我不得不大量修改您的代码,但这可以满足您的要求。您需要将触发的 mousedown 事件传递到添加的 div 上的触发器中。这是新的jsfiddle

This should be your html

这应该是你的html

<html>
<head>  
</head>
<body>
<div id="page_wrap">
<div class="demo" style="width: 300px; height: 200px; background-color: blue; overflow-y: auto; overflow-x: hidden;">
<div id="inactive_dragable" class="ui-widget-content">
    <p>Drag me around</p>
</div>
Lorem ipsum dolor sit amet...</div>
</div>
</body>
</html>

Here is your javascript

这是你的javascript

$(".demo").mousedown(function (e){
    var isIE = document.all ? true : false;
        var _x,_y;
        if (!isIE) {
            _x = e.pageX;
            _y = e.pageY;
        }
        if (isIE) {
            _x = e.clientX + document.body.scrollLeft;
            _y = e.clientY + document.body.scrollTop;
        }
        var boundry = $('#page_wrap').offset();
        $('<div/>', {
            id: 'tester',
        }).addClass('test_drag')
        .html("New div to drag")
        .css("top", _y + "px")
        .css("left", _x + "px")
        .draggable()                 
        .appendTo('#page_wrap');
        $("#tester").trigger(e); //this is the important line, that triggers the drag
});

And your CSS

还有你的 CSS

#inactive_dragable { width: 50px; height: 50px; padding: 0.5em; background-color: green; }
.test_drag { width: 50px; height: 50px; padding: 0.5em; background-color: red; position: absolute; }

回答by Jimmery

ok. after reading your comments i think i understand what you are trying to do, however i dont think there is a "start drag" method which we can use in jquery.

行。阅读您的评论后,我想我明白您要做什么,但是我不认为有我们可以在 jquery 中使用的“开始拖动”方法。

but how about this, instead of binding a mousedown event on div A which creates the new div B and then trying to drag div B, why not remove the mousedown event altogether and replace it with a draggable event, and fire off some code at the beginning of the drag event.

但是这样如何,与其在创建新 div B 的 div A 上绑定 mousedown 事件,然后尝试拖动 div B,为什么不完全删除 mousedown 事件并将其替换为可拖动事件,然后在拖动事件的开始。

for example:

例如:

$(".selector").draggable({
  appendTo:'body',
  addClasses:'',
  scroll:false,
  start:function(){
    //your code here
    //eg:
    $(this).html('something else');
  }
});

the addClasses bit can change the appearance of your div, and the start event can fire off some code to alter div A (which you are now dragging) to appear like your intended div B.

addClasses 位可以改变你的 div 的外观,并且 start 事件可以触发一些代码来改变 div A(你现在正在拖动)看起来像你想要的 div B。

EDIT: the scroll:false bit should get around the problems you are having with the "overflow:auto" parent div.

编辑:scroll:false 位应该可以解决您在“溢出:自动”父 div 中遇到的问题。

its a bit of a work around, but should give you the functionality you are after (assuming i understand you correctly this time!! :)

它有点变通,但应该给你你所追求的功能(假设我这次理解你正确!!:)

回答by Reinstate Monica Cellio

The above answers are better because they're discussing doing it the correct way. However, to literally answer your question, you can trigger the mousedown event as such...

上面的答案更好,因为他们正在讨论以正确的方式做这件事。但是,要从字面上回答您的问题,您可以触发 mousedown 事件...

$("div#divID").trigger("mousedown");

回答by Radu Simionescu

The concept of creating a clone which is to be dragged is already implemented in the draggable plugin. You should have used it like so:

在可拖动插件中已经实现了创建要拖动的克隆的概念。你应该像这样使用它:

$('#tester').draggable({helper: 'clone', appendTo: 'body'});

The appendTo option represents the element where you want the helper to be created

appendTo 选项表示您希望在其中创建助手的元素

You can hide your initial dragged object on dragstart (or leave it there if you desire) Here is a jsFiddle I made as a sample: http://jsfiddle.net/HnpbX/6/

您可以在 dragstart 上隐藏您的初始拖动对象(如果您愿意,也可以将其留在那里)这是我作为示例制作的 jsFiddle:http: //jsfiddle.net/HnpbX/6/

If you want to achieve a functionality of dragging and dropping an element from one container to another, you should use the droppable in combination with draggable

如果要实现将元素从一个容器拖放到另一个容器的功能,则应将 droppable 与 draggable 结合使用