javascript - vanilla js上的拖放鼠标移动脚本
问题描述
我正在编写一个拖放脚本,用于拖放带有“.draggable”类的块。问题是块会定期粘在光标上并且不会脱落。如何编辑此脚本,以便可以用鼠标拖动所有具有“.draggable”类的块而不会出现此问题?
let elements = document.querySelectorAll('.draggable');
elements.forEach(function(el) {
let mover = false,
x, y, posx, posy, first = true;
el.onmousedown = function() {
mover = true;
};
el.onmouseup = function() {
mover = false;
first = true;
};
el.parentNode.onmousemove = function(e) {
el.style.cursor = "move";
if (mover) {
if (first) {
x = e.offsetX;
y = e.offsetY;
first = false;
}
posx = e.pageX - x;
posy = e.pageY - y;
el.style.left = posx + 'px';
el.style.top = posy + 'px';
}
}
});
.draggable {
position: absolute;
z-index: 1;
top: 100px;
}
<section class="dragscroll">
<div class="draggable">
<textarea></textarea>
</div>
</section>
<section class="dragscroll">
<div class="draggable">
<textarea></textarea>
</div>
</section>
解决方案
很难说这很难产生错误,所以请让我知道它有效。我所做的只是
document.addEventListener("mouseup", function() {
mover = false;
first = true;
});
let elements = document.querySelectorAll('.draggable');
elements.forEach(function(el) {
let mover = false,
x, y, posx, posy, first = true;
el.onmousedown = function() {
mover = true;
};
document.addEventListener("mouseup", function() {
mover = false;
first = true;
});
/*
document.onmouseup = function() {
mover = false;
first = true;
};
*/
el.parentNode.onmousemove = function(e) {
el.style.cursor = "move";
if (mover) {
if (first) {
x = e.offsetX;
y = e.offsetY;
first = false;
}
posx = e.pageX - x;
posy = e.pageY - y;
el.style.left = posx + 'px';
el.style.top = posy + 'px';
}
}
});
.draggable {
position: absolute;
z-index: 1;
top: 100px;
}
<section class="dragscroll">
<div class="draggable">
<textarea></textarea>
</div>
</section>
<section class="dragscroll">
<div class="draggable">
<textarea></textarea>
</div>
</section>
推荐阅读
- c# - ExecuteNonQuery 代码成功时返回 -1
- swift - 斯威夫特:完美的记忆可能吗?
- java - Swing 组件自动更改为 AWT
- javascript - TypeError:无法读取未定义的属性“eslint”
- javascript - 如何在节点 cli 中关闭 repl.start() 实例
- android - Samsung Knox 的隐式广播异常
- python - 为什么将长列表转换为 Pandas DataFrame 时会出现 IndexError?
- jquery - 如何隐藏一行你拥有的文本,jQuery?
- angular - wordpress 喜欢静态主页和角度 4 中的其他动态页面
- scala - 了解 Akka 调度程序