siyuan/app/src/util/setPosition.ts
2023-01-24 19:36:45 +08:00

28 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {Constants} from "../constants";
export const setPosition = (element: HTMLElement, x: number, y: number, targetHeight = 0, targetLeft = 0) => {
element.style.top = y + "px";
element.style.left = x + "px";
const rect = element.getBoundingClientRect();
// 上下超出屏幕
if (rect.bottom > window.innerHeight || rect.top < Constants.SIZE_TOOLBAR_HEIGHT) {
const top = y - rect.height - targetHeight;
if (top > Constants.SIZE_TOOLBAR_HEIGHT && (top + rect.height) < window.innerHeight) {
// 上部
element.style.top = top + "px";
} else if (top <= Constants.SIZE_TOOLBAR_HEIGHT) {
// 位置超越到屏幕上方外时需移动到屏幕顶部。eg光标在第一个块然后滚动到上方看不见的位置按 ctrl+a
element.style.top = Constants.SIZE_TOOLBAR_HEIGHT + "px";
} else {
// 依旧展现在下部,只是位置上移
element.style.top = Math.max(Constants.SIZE_TOOLBAR_HEIGHT, window.innerHeight - rect.height) + "px";
}
}
if (rect.right > window.innerWidth) {
// 展现在左侧
element.style.left = `${window.innerWidth - rect.width - targetLeft}px`;
} else if (rect.left < 0) {
// 依旧展现在左侧,只是位置右移
element.style.left = "0";
}
};