如上图所示,图中的虚线框就是需要跟随鼠标移动的div元素,div元素跟随鼠标移动已经实现,但是如果鼠标移动太快,div元素会跟不上,这个问题该如何优化?
全部代码可访问github获取
部分实现代码如下:
let selector = document.getElementById('selector');// 获取虚线框
let moveStartPoint = {x: 0, y: 0};// 鼠标移动起点
let selectorLocation = {x: 150, y: 150};// 虚线框的位置
selector.onmousedown = function (event) {
moveStartPoint.x = event.clientX;
moveStartPoint.y = event.clientY;
selectorLocation.x = selector.offsetLeft;
selectorLocation.y = selector.offsetTop;
};
selector.onmousemove = function (event) {
compute();
};
function compute() {
if (movable) {
let leftLocation = event.clientX - moveStartPoint.x + selectorLocation.x;
let topLocation = event.clientY - moveStartPoint.y + selectorLocation.y;
// 限制虚线框移动范围
if (leftLocation <= 0 || leftLocation >= 298) {
if (leftLocation <= 0) {
leftLocation = 0;
} else {
leftLocation = 298;
}
}
if (topLocation <= 0 || topLocation >= 298) {
if (topLocation <= 0) {
topLocation = 0;
} else {
topLocation = 298;
}
}
selector.style.left = leftLocation + 'px';
selector.style.top = topLocation + 'px';
}
}