0

我创建了以下 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`;
  });

但是当它出现时,它的一部分出现在网站页面后面......如何解决这个问题? 在此处输入图像描述

4

1 回答 1

1

当光标靠近页面边缘时,您需要将其设置为el.style.left0px所以,替换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`;
于 2021-01-28T11:49:29.837 回答