要使鼠标能够拉出选择范围,请在选择后释放鼠标并显示width
和height
的{{1}}和X-axis
的值在这四个字段中选择的区域。
这是我的问题。我希望你能帮助我。谢谢。
答案 0 :(得分:0)
我为可能的解决方案之一创建了小码笔,您需要根据情况进行调整。
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 = 'blue';
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
}
}