HTML 元素出现在页面边缘之外

HTML element appears out of the pages edge

我创建了以下 HTML 元素:

<div classname='PopUp> </div>

我给了它以下 CSS 属性:

.PopUp{
padding: 8px 7px 6px;
          position: absolute;
          z-index: 1;
          top: -10000px;
          left: -10000px;
          margin-top: -6px;
          opacity: 0;
          background-color: gray;
          border-radius: 4px;
          transition: opacity 0.75s;
}

现在我让它相对于鼠标光标活塞弹出,我给了它以下规则:

import {
  Range,
  Editor,
  Transforms,
  createEditor,
  Node,
  Element as SlateElement,
} from "slate";

React.useEffect(() => {
    const el = ref.current;
    const { selection } = editor;

    if (!el) {
      return;
    }

    if (
      !selection ||
      !ReactEditor.isFocused(editor) ||
      Range.isCollapsed(selection) ||
      Editor.string(editor, selection) === ""
    ) {
      el.removeAttribute("style");
      return;
    }

    const domSelection = window.getSelection()!;
    const domRange = domSelection.getRangeAt(0);
    const rect = domRange.getBoundingClientRect();
    el.style.opacity = "1";
    el.style.top = `${rect.top + window.pageYOffset - el.offsetHeight}px`;
    el.style.left = `${
      rect.left + window.pageXOffset - el.offsetWidth / 2 + rect.width / 2
    }px`;
  });

但是当它出现时,它的一部分出现在网站页面后面...如何解决?

当光标关闭页面处于边缘时,您需要将 el.style.left 设置为 0px。因此,将 el.style.left = ${rect.left + window.pageXOffset - el.offsetWidth / 2 + rect.width / 2}px 替换为

const position = rect.left + window.pageXOffset - el.offsetWidth / 2 + rect.width / 2;
el.style.left = `${position < 0 ? 0 :position}px`;