Как я могу создать стабильный перетаскиваемый элемент? - PullRequest
0 голосов
/ 13 июля 2020

Итак, я создал простой скрипт для перетаскиваемого элемента. Проблема в том, что когда я двигаю мышью быстрее, элемент теряется из фокуса.

Есть ли способ сделать это стабильным, независимо от того, как быстро я двигаю мышью ??

Вот настоящая демонстрация, которую я создал: 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>

1 Ответ

0 голосов
/ 13 июля 2020

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>

Я получил этот код от https://jsfiddle.net/tovic/Xcb8d/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...