首页 > 解决方案 > 如何创建稳定的可拖动元素?

问题描述

所以我为可拖动元素创建了简单的脚本。 问题是当我更快地移动鼠标时,元素会从焦点中丢失。

无论我移动鼠标多快,有没有办法让它稳定?

这是我创建的实际演示: 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>

标签: javascripthtmlcssvue.js

解决方案


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/得到这段代码


推荐阅读