javascript - 如何创建稳定的可拖动元素?
问题描述
所以我为可拖动元素创建了简单的脚本。 问题是当我更快地移动鼠标时,元素会从焦点中丢失。
无论我移动鼠标多快,有没有办法让它稳定?
这是我创建的实际演示: https ://www.w3schools.com/code/tryit.asp?filename=GGPV1ESRELL8
<html>
<head>
<style>
.tester {
position: absolute;
width: 150px;
height: 150px;
box-shadow: 0 0 10px black;
background-color: white;
cursor: pointer;
}
</style>
</head>
<body>
<div class='tester'></div>
<script>
let tester = document.querySelector('.tester');
let draggable = false;
let offX;
let offY;
tester.onmousedown = (e) => {
e = e || window.event;
offX = e.offsetX;
offY = e.offsetY;
draggable = true;
tester.style.backgroundColor = 'indigo';
}
tester.onmouseup = () => {
draggable = false;
tester.style.backgroundColor = 'white';
}
document.body.onmousemove = (e) => {
e = e || window.event;
if (draggable){
tester.style.left = (e.pageX - offX) + 'px';
tester.style.top = (e.pageY - offY) + 'px';
}
}
</script>
</body>
</html>
解决方案
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-element').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
body {padding:10px}
#draggable-element {
width:100px;
height:100px;
background-color:#666;
color:white;
padding:10px 12px;
cursor:move;
position:relative; /* important (all position that's not `static`) */
}
<div id="draggable-element">Drag me!</div>
推荐阅读
- javascript - 有没有办法在浏览器中使用跨域字体构建 svg?
- java - 如何解决无法驱动../selenium-server-standalone-3.141.59.jar 的模块描述
- flask - 在应用程序中访问\读取 Flask 环境变量
- kubernetes - Istio 允许外部流量在没有 ServiceEntry 的情况下通过?
- python - VSCode 在 linter 中无法解析导入“sys”
- bash - Sed-替换紧接在特定模式之后的下一个字符串单词,但仅在文件中第一次出现
- c# - System.Random 的多个实例是否仍然在 .Net Core 中使用相同的种子?
- git - 重命名master但保留分支历史
- histogram - influxdb 通量中的非累积直方图函数
- pyspark - PySpark 添加 ID 列和过滤器损坏