如何解决交换位置,例如在Windows任务栏中移动元素纯JavaScript
我编写了这段代码,使类draggable
的任何元素都可拖动。
const d = document.getElementsByClassName("draggable");
for (let i = 0; i < d.length; i++) {
d[i].style.position = "relative";
}
function filter(e) {
let target = e.target;
if (!target.classList.contains("draggable")) {
return;
}
target.moving = true;
e.clientX ?
(target.oldX = e.clientX,target.oldY = e.clientY) :
(target.oldX = e.touches[0].clientX,target.oldY = e.touches[0].clientY)
target.oldLeft = window.getComputedStyle(target).getPropertyValue('left').split('px')[0] * 1;
target.oldTop = window.getComputedStyle(target).getPropertyValue('top').split('px')[0] * 1;
document.onmousemove = dr;
document.addEventListener('touchmove',dr,{passive: false})
function dr(event) {
event.preventDefault();
if (!target.moving) {
return;
}
event.clientX ?
(target.distX = event.clientX - target.oldX,target.distY = event.clientY - target.oldY) :
(target.distX = event.touches[0].clientX - target.oldX,target.distY = event.touches[0].clientY - target.oldY)
target.style.left = target.oldLeft + target.distX + "px";
target.style.top = target.oldTop + target.distY + "px";
}
function endDrag() {
target.moving = false;
}
target.onmouseup = endDrag;
target.ontouchend = endDrag;
}
document.onmousedown = filter;
document.ontouchstart = filter;
div {
width: 100px;
height: 100px;
background: red;
}
<div class="draggable"></div>
tl; dr-我想做一个Windows任务栏的东西,其中元素可以移动,其他元素根据被拖动元素接近的位置向右或向左移动。
我希望可拖动元素捕捉到网格,类似于在Windows任务栏上拖动图标或在浏览器中的另一个选项卡上拖动选项卡时发生的情况。
以下是我的尝试。我删除了沿垂直轴的移动并触摸了支撑以使代码更具可读性。捕捉工作正常,但是被悬停的元素没有移动到另一个空间。
const d = document.getElementsByClassName("draggable");
let grid = 50;
for (let i = 0; i < d.length; i++) {
d[i].style.position = "relative";
d[i].onmousedown = filter;
}
function filter(e) {
let target = e.target;
target.moving = true;
target.oldX = e.clientX;
target.oldLeft = window.getComputedStyle(target).getPropertyValue('left').split('px')[0] * 1;
document.onmousemove = dr;
function dr(event) {
event.preventDefault();
if (!target.moving) {
return;
}
target.distX = event.clientX - target.oldX;
target.style.left = target.oldLeft + Math.round(target.distX / grid) * grid + 'px'
}
function endDrag() {
target.moving = false;
}
document.onmouseup = endDrag;
}
.parent {
width: 100%;
height: 100%;
background: lime;
display: flex;
align-items: center;
}
.child {
width: 50px;
height: 50px;
position: relative;
}
.one {
background: red;
}
.two {
background: blue;
}
<div class="parent">
<div class="child one draggable"></div>
<div class="child two draggable"></div>
</div>
此外,我认为在拖动元素时检查鼠标何时跨过div
宽度的一半,div
应该根据向左移动还是向右移动一个单位。元素位于要拖动的元素的左侧或右侧。检查部分没有问题。我们可以只比较元素offsetLeft
的大小。但是如何使元素移动?
请尝试使用普通JavaScript回答。
编辑:1.更新代码2.更新标题3.更新tl; dr并更改标题3.添加更多标签解决方法
方法1:从问题继续的纯JS代码
以下代码满足了问题的要求。我在原始代码中添加了更多元素(更多元素=更多乐趣)。我还在代码中添加了注释。我相信您只要阅读一下就能理解代码。无论如何,这是一个简短的解释。
在网格中捕捉target
我们首先需要将元素捕捉到网格中。 我们首先捕捉target
,有关捕捉其他元素的信息,请参阅下一节。在行let grid = ...
中指定网格的像素宽度。对于平滑的动画,我们希望target
在结束拖动时而不是在拖动时捕捉。函数endDrag
中的这一行代码在拖动结束后将target
捕捉到网格中。
target.style.left = target.oldLeft + Math.round(target.distX / grid) * grid + "px";
基于target
移动其他元素
我们还需要移动其位置target
的元素。否则,它们将重叠。函数moveElementAt
完成了这项工作。这就是moveElementAt
中发生的事情。
- 我们命名与
target
的左上角elementAt
发生冲突的任何元素。 JavaScript属性.elementFromPoint
进行检查。 - 在检查中,我们通过将CSS
target
设置为pointer-events
来排除none
本身。如果elementAt
是父元素,我们什么也不做。 - 我们通过某种数学逻辑检查元素是从左还是从右向
elementAt
逼近。- 如果
target
是从右侧来的,则elementAt
将grid
个单位向右移动。 - 如果
target
是从左侧来的,elementAt
将向左移动grid
个单位。
- 如果
const d = document.getElementsByClassName("draggable");
let grid = 50; //Width of one grid box
for (let i = 0; i < d.length; i++) {
d[i].style.position = "relative";
}
function filter(e) {
let target = e.target;
target.moving = true;
target.oldX = e.clientX;
target.oldLeft =
window
.getComputedStyle(target)
.getPropertyValue("left")
.split("px")[0] * 1; //Get left style as a number
document.onmousemove = dr;
function dr(event) {
event.preventDefault();
if (!target.moving) {
return;
}
target.distX = event.clientX - target.oldX;
target.style.left = target.oldLeft + target.distX + "px";
target.style.pointerEvents = "none"; //Stops target from being elementAt
moveElementAt();
}
function endDrag() {
target.moving = false;
target.style.left =
target.oldLeft + Math.round(target.distX / grid) * grid + "px";
moveElementAt(); //Do it at endDrag() also to stop elements from overlapping
target.style.pointerEvents = "auto";
}
function moveElementAt() {
let rootEl = target.parentNode;
let elementAt = document.elementFromPoint(
target.offsetLeft,target.offsetTop //Get element at target's coordinates
);
if (elementAt === rootEl) {
return
} //Stop rootEl from moving
//Move elementAt either grid units left or right depending on which way target is approaching it from
if (target.offsetLeft - elementAt.offsetLeft * 1 <= grid / 2) //Can also compare to 0,comparing to grid/2 stops elements' position from breaking when moving very fast to some extent
{
elementAt.style.left =
window
.getComputedStyle(elementAt)
.getPropertyValue("left")
.split("px")[0] * 1 - grid + "px";
} else {
elementAt.style.left =
window
.getComputedStyle(elementAt)
.getPropertyValue("left")
.split("px")[0] * 1 + grid + "px";
}
}
document.onmouseup = endDrag;
}
document.onmousedown = filter;
.parent {
width: 100%;
height: 100%;
background: lime;
display: flex;
align-items: center;
}
.child {
width: 50px;
height: 50px;
position: relative;
}
.one {
background: red;
}
.two {
background: blue;
}
.three {
background: brown;
}
.four {
background: pink;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Hello!</title>
<link rel="stylesheet" href="/style.css" />
<script src="/scriptmain.js"></script>
</head>
<body>
<div class="parent" id="parent">
<div class="child one draggable"></div>
<div class="child two draggable"></div>
<div class="child three draggable"></div>
<div class="child four draggable"></div>
</div>
</body>
</html>
以异常快的速度拖动时,代码会出现故障。我稍后会修复故障。
方法2:使用拖放API /库
Jon Nezbit通知我,有一个名为SortableJs的库专门用于此目的。提出了有关纯JS解决方案的问题。因此,我编写了一种使用拖放API的方法。这是一个片段。
function sortable(rootEl) {
let dragEl;
for (let i = 0; i < rootEl.children.length; i++) {
rootEl.children[i].draggable = true;
}
rootEl.ondragstart = evt => {
dragEl = evt.target;
rootEl.addEventListener("dragover",onDragOver);
rootEl.addEventListener("dragend",onDragEnd);
};
function onDragOver(evt) {
let target = evt.target;
rootEl.insertBefore(
dragEl,rootEl.children[0] === target ?
rootEl.children[0] :
target.nextSibling || target
);
}
function onDragEnd(evt) {
evt.preventDefault();
rootEl.removeEventListener("dragover",onDragOver);
rootEl.removeEventListener("dragend",onDragEnd);
}
}
sortable(document.getElementById("parent"))
.parent {
width: 100%;
height: 100%;
background: lime;
display: flex;
align-items: center;
}
.child {
width: 50px;
height: 50px;
position: relative;
}
.one {
background: red;
}
.two {
background: blue;
}
.three {
background: brown;
}
.four {
background: pink;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Hello!</title>
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<div class="parent" id="parent">
<div class="child one draggable"></div>
<div class="child two draggable"></div>
<div class="child three draggable"></div>
<div class="child four draggable"></div>
</div>
<script src="/script-dndmain.js"></script>
</body>
</html>
该库使用HTML拖放API,该API无法为我提供所需的结果。但您绝对应该检查一下。另外,请查阅该库作者的this优秀文章,该文章(使用纯js解释了他们是如何创建该库的)。尽管我没有使用它,但我相信有人会得到帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。