我想制作一个jQuery插件,允许您拖拽和绘制一个矩形(或带有边框的div),但我不确定如何做。我不知道是否已经有这种功能的插件,因此不知道在哪里找到示例来完成此操作。
如何在jQuery中实现拖放与绘制?
如何在jQuery中实现拖放与绘制?
像这样的东西的基础知识相当简单,当你思考它时:
mousedown
事件;event
对象中的鼠标坐标(e.pageX
和e.pageY
);mousemove
事件,以根据鼠标坐标更改width
和height
对象;mouseup
事件以分离mousemove
事件侦听器。前面提到的绝对定位元素是一个带有边框和background: transparent
的<div>
,例如:
更新: 这里有一个示例:
$(function() {
var $container = $('#container');
var $selection = $('<div>').addClass('selection-box');
$container.on('mousedown', function(e) {
var click_y = e.pageY;
var click_x = e.pageX;
$selection.css({
'top': click_y,
'left': click_x,
'width': 0,
'height': 0
});
$selection.appendTo($container);
$container.on('mousemove', function(e) {
var move_x = e.pageX,
move_y = e.pageY,
width = Math.abs(move_x - click_x),
height = Math.abs(move_y - click_y),
new_x, new_y;
new_x = (move_x < click_x) ? (click_x - width) : click_x;
new_y = (move_y < click_y) ? (click_y - height) : click_y;
$selection.css({
'width': width,
'height': height,
'top': new_y,
'left': new_x
});
}).on('mouseup', function(e) {
$container.off('mousemove');
$selection.remove();
});
});
});
$("#YOUR_ELEMENT_ID").on("mousedown", function (e) {
var click_x = e.pageX;
var click_y = e.pageY;
/* Posição do objeto */
var x = parseFloat($(this).css("left").replace("px", "")),
y = parseFloat($(this).css("top").replace("px", ""));
/* Calcula distância no eixo x */
var distanc_x = Math.abs(x - click_x);
var distanc_y = Math.abs(y - click_y);
$("#YOUR_ELEMENT_ID")
.on("mousemove", function (e) {
var new_x = e.pageX - distanc_x;
var new_y = e.pageY - distanc_y;
$(this).css({
top: new_y,
left: new_x,
});
}).on("mouseup", function (e) {
$(this).off("mousemove");
});
});