首页 > 解决方案 > JS 可调整大小的 div

问题描述

我想创建div类似于在 Windows 桌面上单击和拖动的元素。

到目前为止,我的代码执行以下操作:

我的问题是调整大小部分。现在,div 只能在东南方向展开。

参考这个Fiddle一个例子。

玩弄 Fiddle 示例以了解我的意思(例如,您不能垂直扩展超出原点)。

我认为原因是因为newX并且newY是负值。我该如何解决这个问题?

标签: javascripthtml

解决方案


你还没有考虑鼠标移动坐标小于绘图起始坐标的情况,我对JS代码做了一点修改,

var clientBox = document.getElementById("userBox");
var startX, startY, currentX, curentY;

function initRect(event) {
    startX = event.clientX;
    startY = event.clientY;
    window.addEventListener("mousemove", drawRect);
    window.addEventListener("mouseup", dstryRect);

}

function drawRect(event) {
    var width = event.clientX-startX;
    var height = event.clientY-startY;
    var x = startX;
    var y = startY;
    if (width < 0) {
        x = startX + width;
        width=-width;
    }
    if (height < 0) {
        y = startY + height;
        height = -height;
    }
    clientBox.style.display = "block";   // Hideen until click detected
    clientBox.style.top  = y + "px";
    clientBox.style.left = x + "px";
    clientBox.style.width = width + "px";
    clientBox.style.height = height + "px";
}

function dstryRect() {
    window.removeEventListener("mousemove", drawRect);
    window.removeEventListener("mouseup", dstryRect);
    clientBox.style.display = "none";
    clientBox.style.height = "0px";
    clientBox.style.width = "0px";
}

只需在 JS 文件中更新这些更改即可。这是工作小提琴 谢谢。


推荐阅读