我写了自己的可拖动的&可调整大小的代码,
var startX, startY, startWidth, startHeight;
var div = document.getElementById('div'),
x1 = 0,
y1 = 0,
x2 = 0,
y2 = 0;
var element;
function reCalc() {
var x3 = Math.min(x1, x2);
var x4 = Math.max(x1, x2);
var y3 = Math.min(y1, y2);
var y4 = Math.max(y1, y2);
div.style.left = x3 + 'px';
div.style.top = y3 + 'px';
div.style.width = x4 - x3 + 'px';
div.style.height = y4 - y3 + 'px';
}
$(document).on("mousedown", function (e) {
var target = $(event.target);
x1 = e.clientX;
y1 = e.clientY;
if (element && element.find('.resizer').is(target)) {
return;
}
if (element) {
element.remove();
}
div.hidden = 0;
x1 = e.clientX;
y1 = e.clientY;
reCalc();
});
$(document).on("mousemove", function (e) {
x2 = e.clientX;
y2 = e.clientY;
reCalc();
});
$(document).on("mouseup", function (e) {
div.hidden = 1;
var target = $(event.target);
if (element && element.find('.resizer').is(target)) {
return;
}
element = $("<div>");
element[0].style.left = div.style.left;
element[0].style.top = div.style.top;
element[0].style.width = div.style.width;
element[0].style.height = div.style.height;
var resizer = document.createElement('div');
resizer.className = 'resizer';
element.append(resizer);
resizer.addEventListener('mousedown', initDrag, false);
$("body").append(element.show());
element.on("mousedown", function () {
event.stopImmediatePropagation();
});
element.on("mouseup", function () {
event.stopImmediatePropagation();
});
});
function initDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(element[0]).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(element[0]).height, 10);
document.documentElement.addEventListener('mousemove', doDrag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function doDrag(e) {
element[0].style.width = (startWidth + e.clientX - startX) + 'px';
element[0].style.height = (startHeight + e.clientY - startY) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', doDrag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
但是当我调整大小时,它无法正确处理mousedown事件。当我鼠标移动时它应该停止拖动
任何解决方案??
答案 0 :(得分:5)
没有侦听器可以调用您的stopDrag()
函数:
resizer.addEventListener('mousedown', initDrag, false);
// Add
resizer.addEventListener('mouseup', stopDrag, false);