Chrome/Firefox 中的 Rect 函数有什么用

What is Rect function in Chrome/Firefox for?

本文关键字:什么 函数 Rect Firefox 中的 Chrome      更新时间:2023-09-26

我偶然发现了Rect()函数,它存在于Firefox和Chrome(但不是IE 10)中:

typeof Rect; // "function"
Rect;        // function Rect() { [native code] }

但是这个函数既不能直接访问,也不能作为构造函数访问:

Rect();     // TypeError: Illegal constructor
new Rect(); // TypeError: Illegal constructor

这个函数的目的是什么?

> Rect 是在文档对象模型 (DOM) 级别 2 样式规范中定义的接口,用于处理 DOM 绑定中的 CSS rect()(例如浏览器中的 Javascript DOM 绑定)。

正如您所注意到的,您不能自己将其作为构造函数调用,但是实现此接口的对象由各种函数返回,例如 .getRectValue()

function doSomething(v) {
  if (v instanceof Rect) {
    ...
  }
  else {
    ...
  }
}
doSomething(window.getComputedStyle(elem, null).
  getPropertyCSSValue(styleProp).getRectValue());

现在你可以创建一个 DOMRect:

var myDOMRect = new DOMRect(x, y, width, height);

见 https://developer.mozilla.org/en-US/docs/Web/API/DOMRect/DOMRect