Untitled
unknown
plain_text
10 months ago
2.6 kB
13
Indexable
const styleSheet = document.createElement('style');
styleSheet.textContent = `
.resizable {
position: relative;
}
.resize-handle {
position: absolute;
right: -2px;
top: 0;
bottom: 0;
width: 4px;
cursor: col-resize;
background-color: #ddd;
z-index: 100;
}
.resize-handle:hover,
.resize-handle.active {
background-color: #0066cc;
}
.resizing {
user-select: none;
cursor: col-resize;
}
`;
document.head.appendChild(styleSheet);
const flexContainer = document.querySelectorAll('.flex')[1];
const columns = Array.from(flexContainer.children);
function setupResize(column, handle, index) {
let startX, startWidth, nextStartWidth;
const startResize = (e) => {
e.preventDefault();
startX = e.clientX || e.touches?.[0]?.clientX;
startWidth = column.offsetWidth;
nextStartWidth = columns[index + 1]?.offsetWidth;
handle.classList.add('active');
document.body.classList.add('resizing');
document.addEventListener('mousemove', resize);
document.addEventListener('touchmove', resize, { passive: false });
document.addEventListener('mouseup', stopResize);
document.addEventListener('touchend', stopResize);
};
const resize = (e) => {
e.preventDefault();
const clientX = e.clientX || e.touches?.[0]?.clientX;
const diff = clientX - startX;
const containerWidth = flexContainer.offsetWidth;
const newWidth = ((startWidth + diff) / containerWidth * 100);
const nextNewWidth = nextStartWidth ? ((nextStartWidth - diff) / containerWidth * 100) : null;
if (newWidth > 10 && (!nextNewWidth || nextNewWidth > 10)) {
column.style.width = `${newWidth}%`;
if (columns[index + 1]) {
columns[index + 1].style.width = `${nextNewWidth}%`;
}
}
};
const stopResize = () => {
handle.classList.remove('active');
document.body.classList.remove('resizing');
document.removeEventListener('mousemove', resize);
document.removeEventListener('touchmove', resize);
document.removeEventListener('mouseup', stopResize);
document.removeEventListener('touchend', stopResize);
};
handle.addEventListener('mousedown', startResize);
handle.addEventListener('touchstart', startResize, { passive: false });
}
columns.forEach((column, index) => {
column.classList.add('resizable');
const handle = document.createElement('div');
handle.className = 'resize-handle';
column.appendChild(handle);
setupResize(column, handle, index);
});Editor is loading...
Leave a Comment