Skip to content

虚拟元素

¥Virtual Elements

相对于自定义参考区域定位浮动元素,这对于上下文菜单、范围选择、跟随光标等非常有用。

¥Position a floating element relative to a custom reference area, useful for context menus, range selections, following the cursor, and more.

用法

¥Usage

最基本的虚拟元素是一个具有 getBoundingClientRect 方法的普通对象,它模模拟实元素的方法:

¥The most basic virtual element is a plain object that has a getBoundingClientRect method, which mimics a real element’s one:

// A virtual element that is 20 x 20 px starting from (0, 0)
const virtualEl = {
  getBoundingClientRect() {
    return {
      x: 0,
      y: 0,
      top: 0,
      left: 0,
      bottom: 20,
      right: 20,
      width: 20,
      height: 20,
    };
  },
};
computePosition(virtualEl, floatingEl);

点引用(例如鼠标事件)就是这样的用例之一:

¥A point reference, such as a mouse event, is one such use case:

function onClick({clientX, clientY}) {
  const virtualEl = {
    getBoundingClientRect() {
      return {
        width: 0,
        height: 0,
        x: clientX,
        y: clientY,
        top: clientY,
        left: clientX,
        right: clientX,
        bottom: clientY,
      };
    },
  };
 
  computePosition(virtualEl, floatingEl).then(({x, y}) => {
    // Position the floating element relative to the click
  });
}
 
document.addEventListener('click', onClick);

contextElement

如果你的 getBoundingClientRect 方法派生自真实元素,则此属性非常有用,以确保剪切和位置更新检测按预期工作。

¥This property is useful if your getBoundingClientRect method is derived from a real element, to ensure clipping and position update detection works as expected.

const virtualEl = {
  getBoundingClientRect() {
    return {
      // ...
    };
  },
  contextElement: document.querySelector('#context'),
};

getClientRects

当使用范围选择和 inline 中间件时,此属性非常有用。

¥This property is useful when using range selections and the inline middleware.

const virtualEl = {
  getBoundingClientRect: () => range.getBoundingClientRect(),
  getClientRects: () => range.getClientRects(),
};