问题
I have some particular need to clone an element (image) and be draggable inside a container and still retain its draggable (but not clone) once inside.
I want to make only the cloned elements dragged inside the container to also be re-sizable, but I cannot get it to work.
I can only get the parent element to resize. Is there any way to only .resize the cloned element?
Somewhat wonky but working example: http://jsfiddle.net/rGUma/4/
Code:
<div class="drag"><img src="..." /></div>
<div class="drag"><img src="..." /></div>
<div class="drag"><img src="..." /></div>
<div class="drop-zone"></div>
<script>
$(".drop-zone").droppable({
accept: '.drag',
drop: function(event, ui) {
var $clone = ui.helper.clone();
if (!$clone.is('.inside-drop-zone')) {
$(this).append($clone.addClass('inside-drop-zone').draggable({
containment: '.drop-zone'
}));
}
}
});
$(".drag").draggable({
helper: 'clone'
});
//this works but I dont want it on outside elements
$( '.drag' ).resizable({
helper: "ui-resizable-helper"
});
//this doesn't work on cloned images but what I want working
$( '.drop-zone img' ).resizable({
helper: "ui-resizable-helper"
});
// '.inside-drop-zone img' also doesnt work
});
</script>
ps. If someone can explain why it doesn't work it would be greatly appreciated.
回答1:
It doesn't work because the clone is never set to be resizable. The .resizable is only applied to the elements that exist in the beginning, not to any new elements you create.
I move the resizable call into the cloning portion to apply it to the clone. This also means that the outside boxes are not resizable, per your comments int the source (updated jsfiddle):
$(document).ready(function($) {
$(".drop-zone").droppable({
accept: '.drag',
drop: function(event, ui) {
var $clone = ui.helper.clone();
if (!$clone.is('.inside-drop-zone')) {
$(this).append($clone.addClass('inside-drop-zone').draggable({
containment: '.drop-zone'
}));
$clone.resizable({ //this works but I dont want it to on outside elements
helper: "ui-resizable-helper"
});
}
}
});
$(".drag").draggable({
helper: 'clone'
});
$('.drop-zone img').resizable({ //this doesn't work because its cloned "inside" but its what I want working
helper: "ui-resizable-helper"
});
// '.inside-drop-zone img' also doesnt work
//
});
回答2:
Bind the resizable creation to some kind of event when the clone is born?
$('.drop-zone').on('hover', '.drag', function() {
$(this).resizable({
helper: "ui-resizable-helper"
});
});
回答3:
Just use :
$clone.children().resizable({
helper: "ui-resizable-helper"
});
and all images under class: drop-zone will be re-sizable.
来源:https://stackoverflow.com/questions/9815789/how-do-you-resize-a-cloned-jquery-ui-element-image