javascript - JS 可调整大小的 div
问题描述
我想创建div
类似于在 Windows 桌面上单击和拖动的元素。
到目前为止,我的代码执行以下操作:
- 当页面检测到鼠标按下时,我们创建(只是将 display:none 的 CSS 样式更改为 display:block)一个 `div`
- 如果用户在鼠标向下移动的同时移动鼠标,他们会修改 div 的大小。
- 当用户释放鼠标按钮时,我们隐藏 div (display:none)
我的问题是调整大小部分。现在,div 只能在东南方向展开。
参考这个Fiddle一个例子。
玩弄 Fiddle 示例以了解我的意思(例如,您不能垂直扩展超出原点)。
我认为原因是因为newX
并且newY
是负值。我该如何解决这个问题?
解决方案
你还没有考虑鼠标移动坐标小于绘图起始坐标的情况,我对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 文件中更新这些更改即可。这是工作小提琴 谢谢。
推荐阅读
- python - 将 python 字典从 {key : [x, y, z]} 反转为 {x: key, y : key, z : key}
- javascript - MongoDB查找带有日期比较的查询(NodeJs)
- android - 将 Xamarin 应用程序从 Windows 部署到本地手机说成功,但我在手机上看不到该应用程序?
- python - 为什么 concat 方法不匹配多个文件中的列?
- excel - VBA 代码在一个工作簿中工作,但不在另一个工作簿中工作
- c# - 如何在 Blazor 中使用 C# 动态更改 HTML 背景
- javascript - 在javascript中替换字符串中不区分大小写的数组中的值
- swift - 如何在一个控制器中同时调用多个 api
- php - 如何仅使用 PHP 创建字数统计脚本并使用 HTML 创建表单?
- javascript - 将剩余天数转换为年、月、日