如何使用Jquery使future元素可拖动

时间:2021-11-18 18:57:30

I am reading the below api will make the currently available element on a page draggable.

我正在阅读下面的api将使页面上当前可用的元素可拖动。

$( ".draggable" ).draggable({ containment: "parent" });

but in my case I will be constructing new elements based on the user action. Like I will allow them to insert a text box over a image which should be draggable as well.

但在我的情况下,我将基于用户操作构建新元素。就像我允许他们在图像上插入文本框一样,也应该是可拖动的。

Is there a mechanism where I can attach this draggable feature using jquery using ".on()" ?

有没有一种机制,我可以使用“.on()”使用jquery附加这个可拖动的功能?

OR

I have to execute $( "this" ).draggable({ containment: "parent" }); every time when I create a new element?

我必须执行$(“this”)。draggable({containment:“parent”});每当我创建一个新元素?

Thanks for reading

谢谢阅读

1 个解决方案

#1


6  

Is there a mechanism where i can attach this draggable feature using jquery using ".on()" ?

有没有一种机制,我可以使用“.on()”使用jquery附加这个可拖动的功能?

No (well, technically yes), you'll have to make each element draggable after you create it, or after some event that happens after it is created (such as mouseenter)

否(嗯,技术上是),你必须在创建它之后使每个元素都可拖动,或者在创建它之后发生的某些事件之后(例如mouseenter)

$(document).on("mouseenter", ".draggable:not(.initiated)", function() {
    $(this).draggable({ containment: "parent" }).addClass("initiated");
});

the initiated class prevents re-initializing the draggable every time you mouse over.

每次鼠标悬停时,启动的类都会阻止重新初始化拖动。

Note, you should use a better ancestor than document since mousenter is an event that will happen often on the document (will happen any time any element in the dom is moused into).

请注意,您应该使用比文档更好的祖先,因为mousenter是一个经常在文档上发生的事件(将在dom中的任何元素被填入的任何时候发生)。

#1


6  

Is there a mechanism where i can attach this draggable feature using jquery using ".on()" ?

有没有一种机制,我可以使用“.on()”使用jquery附加这个可拖动的功能?

No (well, technically yes), you'll have to make each element draggable after you create it, or after some event that happens after it is created (such as mouseenter)

否(嗯,技术上是),你必须在创建它之后使每个元素都可拖动,或者在创建它之后发生的某些事件之后(例如mouseenter)

$(document).on("mouseenter", ".draggable:not(.initiated)", function() {
    $(this).draggable({ containment: "parent" }).addClass("initiated");
});

the initiated class prevents re-initializing the draggable every time you mouse over.

每次鼠标悬停时,启动的类都会阻止重新初始化拖动。

Note, you should use a better ancestor than document since mousenter is an event that will happen often on the document (will happen any time any element in the dom is moused into).

请注意,您应该使用比文档更好的祖先,因为mousenter是一个经常在文档上发生的事件(将在dom中的任何元素被填入的任何时候发生)。