-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
80 lines (66 loc) · 2.56 KB
/
script.js
File metadata and controls
80 lines (66 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const tableElement = document.getElementById('table');
const cellElements = [...tableElement.getElementsByTagName('td')];
const selectionElement = document.getElementById('selection');
let startPos = null;
const getRect = (point1, point2) => ({
x: Math.min(point1.x, point2.x),
y: Math.min(point1.y, point2.y),
left: Math.min(point1.x, point2.x),
right: Math.max(point1.x, point2.x),
top: Math.min(point1.y, point2.y),
bottom: Math.max(point1.y, point2.y),
width: Math.max(point1.x, point2.x) - Math.min(point1.x, point2.x),
height: Math.max(point1.y, point2.y) - Math.min(point1.y, point2.y)
});
const drawSelection = (start, end) => {
const selectionRect = getRect(start, end);
selectionElement.style.display = 'block';
selectionElement.style.width = `${selectionRect.width}px`;
selectionElement.style.height = `${selectionRect.height}px`;
selectionElement.style.left = `${selectionRect.left}px`;
selectionElement.style.top = `${selectionRect.top}px`;
};
const clearSelection = () => {
selectionElement.style.display = '';
selectionElement.style.width = '';
selectionElement.style.height = '';
selectionElement.style.left = '';
selectionElement.style.top = '';
};
const checkRectIntersection = (rect1, rect2) => !(
rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom
);
const fillCells = (startPos, endPos) => {
const selectionRect = getRect(startPos, endPos);
cellElements.forEach((cellElement) => {
const cellRect = cellElement.getBoundingClientRect();
if (checkRectIntersection(cellRect, selectionRect)) {
cellElement.style.backgroundColor = '#E7ECFF';
} else {
cellElement.style.backgroundColor = '';
}
});
};
const onMouseMove = (event) => {
const endPos = { x: event.clientX, y: event.clientY };
fillCells(startPos, endPos);
drawSelection(startPos, endPos);
};
const onMouseUp = (event) => {
const endPos = { x: event.clientX, y: event.clientY };
fillCells(startPos, endPos);
clearSelection();
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('mouseleave', onMouseUp);
};
const onMouseDown = (event) => {
startPos = { x: event.clientX, y: event.clientY };
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
document.addEventListener('mouseleave', onMouseUp);
};
document.addEventListener('mousedown', onMouseDown);