TypeScript 函数限制可拖动元素在父元素内移动 - 代码示例
TypeScript 函数限制可拖动元素在父元素内移动 - 代码示例
本 TypeScript 函数限制可拖动元素在父元素内移动,即使元素放大到比父元素更大。代码使用鼠标事件检测拖动,并限制元素的位置以避免超出父元素的边界。
interface Position {
x: number;
y: number;
}
function limitMove(child: HTMLElement, parent: HTMLElement): void {
let startPos: Position | null = null;
let endPos: Position | null = null;
let isDragging = false;
child.addEventListener('mousedown', (e: MouseEvent) => {
startPos = {
x: e.clientX,
y: e.clientY,
};
isDragging = true;
});
child.addEventListener('mousemove', (e: MouseEvent) => {
if (!isDragging) {
return;
}
const childRect = child.getBoundingClientRect();
const parentRect = parent.getBoundingClientRect();
const newX = childRect.left + e.clientX - startPos!.x;
const newY = childRect.top + e.clientY - startPos!.y;
if (newX < parentRect.left) {
child.style.left = parentRect.left - childRect.width / 2 + 'px';
} else if (newX + childRect.width > parentRect.right) {
child.style.left = parentRect.right - childRect.width / 2 + 'px';
} else {
child.style.left = newX + 'px';
}
if (newY < parentRect.top) {
child.style.top = parentRect.top - childRect.height / 2 + 'px';
} else if (newY + childRect.height > parentRect.bottom) {
child.style.top = parentRect.bottom - childRect.height / 2 + 'px';
} else {
child.style.top = newY + 'px';
}
endPos = {
x: e.clientX,
y: e.clientY,
};
});
child.addEventListener('mouseup', () => {
startPos = null;
isDragging = false;
});
child.addEventListener('mouseleave', () => {
startPos = null;
isDragging = false;
});
}
这个函数使用了 TypeScript 类型注释和类型别名。
它接受两个参数:子元素和父元素。它使用鼠标事件来检测子元素的拖动,并限制子元素的位置,使其不会超出父元素的边界。如果子元素放大到比父元素大,它将限制子元素的移动,使其不会超出父元素的边界。
使用示例:
<div id='parent' style='position: relative; width: 300px; height: 300px; border: 1px solid black;'>
<div id='child' style='position: absolute; width: 100px; height: 100px; background-color: red; transform: scale(2);'></div>
</div>
<script>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
limitMove(child, parent);
</script>
在这个例子中,子元素是一个红色的 div,它被放置在一个带有黑色边框的父 div 中。子元素被缩放为原来的两倍,因此它比父元素大。当你尝试拖动子元素时,它会被限制在父元素的边界内。
原文地址: https://www.cveoy.top/t/topic/lpqd 著作权归作者所有。请勿转载和采集!