我希望一个元素在从其中心拖动时根据其在父级中的位置调整大小。
问题是可拖动元素在被拖动时会远离光标。
jsfiddle演示应该清楚地说明意图是什么。
Javascript代码:
var ele = document.getElementsByClassName ("target")[0];
var parent = document.getElementsByClassName ("containerParent")[0];
var mouseDownIs = false;
ele.addEventListener ("mousedown" , eleMouseDown , false);
function eleMouseDown () {
mouseDownIs = true;
document.addEventListener ("mousemove" , eleMouseMove , false);
}
function eleMouseMove (ev) {
if (mouseDownIs === true) {
var pX = ev.pageX;
var pY = ev.pageY;
var inParentPosX= pX - parent.offsetLeft;
var inParentPosY= pY - parent.offsetTop;
var mFactor = 0.12; // ratio -> half parent divided by child width
if (inParentPosX > 125) { // first edge case scenario; restrict max size of draggable element (child)
var result = (125 * mFactor);
} else if (inParentPosX <= 25) { // second edge case scenario; restrict min size of draggable element (child)
var result = (25 * mFactor);
} else {
var result = (inParentPosX * mFactor);
}
// This is where things are probably going wrong
var posX = inParentPosX + ((result - 2) / 2); // -2 is for the border value
var posY = inParentPosY + ((result - 2) / 2);
ele.style.left = posX + "px";
ele.style.top = posY + "px";
ele.style.width = result + "px";
ele.style.height= result + "px";
}
document.addEventListener ("mouseup" , eleMouseUp , false);
}
function eleMouseUp () {
mouseDownIs = false;
document.removeEventListener ("mousemove" , eleMouseMove , false);
document.removeEventListener ("mouseup" , eleMouseUp , false);
}
这是我昨天发布的一个问题的转贴,该问题仅获得 13 次浏览。