我目前能够用鼠标在一个区域上创建一个对象并显示该对象的大小和位置。
如果要进一步拖动对象,该怎么做?
我需要您的帮助,谢谢。
曾经想过使用jquery的可拖动对象,但不知道如何开始实现它
let isDragging = false;
const startArr=[];
document.getElementById('target_element').addEventListener('mousedown', function(e){
startArr[0] = e.offsetX;
startArr[1] = e.offsetY;
isDragging=true
})
const currentArr=[]
document.getElementById('target_element').addEventListener('mousemove', function(e){
if (isDragging){
currentArr[0] = e.offsetX;
currentArr[1] = e.offsetY;
const dimensions = getDimensions(startArr, currentArr);
const parentElement = document.getElementById('target_element');
parentElement.innerHTML = '';
const selectWindow = document.createElement('div');
selectWindow.style.position = 'absolute';
selectWindow.style.height = dimensions.h+'px';
selectWindow.style.width = dimensions.w+'px';
selectWindow.style.top = dimensions.y+'px';
selectWindow.style.left = dimensions.x+'px';
selectWindow.style.backgroundColor = '#34f';
parentElement.appendChild(selectWindow);
currentArr.length = 0;
}
})
const finishArr=[];
document.getElementById('target_element').addEventListener('mouseup', function(e){
if (isDragging){
finishArr[0] = e.offsetX;
finishArr[1] = e.offsetY;
const dimensions = getDimensions(startArr, finishArr);
document.getElementById('x').innerText = dimensions.x;
document.getElementById('y').innerText = dimensions.y;
document.getElementById('w').innerText = dimensions.w;
document.getElementById('h').innerText = dimensions.h;
isDragging=false;
}
})
function getDimensions(startingPoint, finishPoint){
const top = Math.min(startingPoint[1], finishPoint[1]);
const bottom = Math.max(startingPoint[1], finishPoint[1]);
const left = Math.min(startingPoint[0], finishPoint[0]);
const right = Math.max(startingPoint[0], finishPoint[0]);
return {
x: left,
y: top,
w: right-left,
h: bottom-top
}
}
<div id="info">
<p>X: <span id="x"></span></p>
<p>Y: <span id="y"></span></p>
<p>W: <span id="w"></span></p>
<p>H: <span id="h"></span></p>
</div>
<div id="target_element" style="width: 800px; height: 600px; background-color: #666; margin:100px; position: relative;">
</div>