Michael L的回答中的小提琴涵盖了基本要素,但仍然包含一些错误/限制。因此,我在这里添加我的修改版本作为答案。
HTML
<div id='container'></div>
CSS
#container {
position: relative;
width: 500px;
height: 500px;
background-color: #eee;
}
.block {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
opacity: 0.2;
}
JavaScript
$("#container").on("mousedown", function(event){
if (event.target !== this) {
return;
}
var $target = $(event.target),
$block = $("<div />")
.addClass("block")
.css({
top: event.pageY - $target.offset().top,
left: event.pageX - $target.offset().left
})
.resizable()
.draggable({ containment: $target });
$target.append($block);
simulateHandleEvent($block, "se", event);
})
function simulateHandleEvent($item, handle, event){
$item.find(".ui-resizable-" + handle)
.trigger("mouseover")
.trigger({
type: "mousedown",
which: 1,
pageX: event.pageX,
pageY: event.pageY
});
}
看看这个 JSFiddle