我有 jQuery UI 可拖动和可调整大小的工作。我正在使用按钮 onClick 函数在我的另一个 div (#canvas) 中创建一个 div。Draggable 适用于我静态添加的 div,但不适用于附加了 onClick 函数的 div。知道为什么吗?
JS
// Draw rectangle
function drawRect(){
var rectangle = document.createElement('div');
rectangle.className = 'rectangle ui-draggable ui-resizable ui-selectable';
rectangle.style.width = "200px";
rectangle.style.height = "200px";
rectangle.style.position = "absolute";
// Define resize handles
var n = document.createElement('div');
n.className = 'ui-resizable-handle ui-resizable-n';
var e = document.createElement('div');
e.className = 'ui-resizable-handle ui-resizable-e';
var s = document.createElement('div');
s.className = 'ui-resizable-handle ui-resizable-s';
var w = document.createElement('div');
w.className = 'ui-resizable-handle ui-resizable-w';
// Build resize handles
rectangle.appendChild(n);
rectangle.appendChild(e);
rectangle.appendChild(s);
rectangle.appendChild(w);
// Build div
document.getElementById("canvas").appendChild(rectangle);
}
jQuery 绑定
jQuery(function($) {
// Make boxes draggable
$('.rectangle').draggable();
// Make elements resizable
$('.rectangle').resizable({
// Set custom resize handles
handles: {'n': '.ui-resizable-n', 'e': '.ui-resizable-e', 's': '.ui-resizable-s', 'w': '.ui-resizable-w' },
// Recalculate dimensions from pixels to percentages
stop: function(e, ui) {
var parent = ui.element.parent();
ui.element.css({
width: ui.element.width()/parent.width()*100+"%",
height: ui.element.height()/parent.height()*100+"%"
});
}
});
HTML
<div id="canvas">
<div class="rectangle ui-draggable ui-resizable ui-selectable"></div>
</div>
<button onClick="drawRect();">click here</button>