CSSPageDescriptors
CSSPageDescriptors 介面表示一個用於 @page at-rule 的 CSS 宣告塊。
該介面公開了頁面的樣式資訊以及各種與樣式相關的方法和屬性。每個多詞屬性都有駝峰式和下劃線式兩種寫法。這意味著,例如,您可以透過 style["margin-top"] 或 style.marginTop(其中 style 是一個 CSSPageDescriptor)來訪問 margin-top CSS 屬性。
可以透過 CSSPageRule 介面的 style 屬性訪問 CSSPageDescriptors 物件,而 CSSPageRule 介面又可以透過 CSSStyleSheet API 找到。
屬性
該介面還繼承了其父介面 CSSStyleDeclaration 的屬性。
margin-
表示相應
@pageat-rule 的margin屬性的字串。 margin-top-
表示相應
@pageat-rule 的margin-top屬性的字串。 marginTop-
表示相應
@pageat-rule 的margin-top屬性的字串。 margin-right-
表示相應
@pageat-rule 的margin-right屬性的字串。 marginRight-
表示相應
@pageat-rule 的margin-right屬性的字串。 margin-bottom-
表示相應
@pageat-rule 的margin-bottom屬性的字串。 marginBottom-
表示相應
@pageat-rule 的margin-bottom屬性的字串。 margin-left-
表示相應
@pageat-rule 的margin-left屬性的字串。 marginLeft-
表示相應
@pageat-rule 的margin-left屬性的字串。 page-orientation實驗性-
表示相應
@pageat-rule 的page-orientation屬性的字串。 pageOrientation實驗性-
表示相應
@pageat-rule 的page-orientation屬性的字串。 size-
表示相應
@pageat-rule 的size屬性的字串。
例項方法
該介面繼承了其父介面 CSSStyleDeclaration 的方法。
示例
檢查 page at-rule
本示例獲取 @page at-rule 的 CSSPageDescriptors(如果瀏覽器支援該物件),然後記錄其屬性。
CSS
下面我們使用 @page at-rule 定義頁面的樣式。我們使用 margin 簡寫為每個 margin 屬性指定不同的值,並指定 size。我們不設定 page-orientation。這使我們能夠看到屬性如何在 Web API 物件中對映。
@page {
margin: 1cm 2px 3px 4px;
/* page-orientation: upright; */
size: A4;
}
JavaScript
首先,我們檢查全域性 window 物件上是否定義了 CSSPageDescriptors,如果沒有,則記錄該介面不受支援。
如果 CSSPageDescriptors 受支援,我們獲取目標樣式表,然後獲取該樣式表中定義的 cssRules。我們需要獲取此樣式表,因為示例嵌入在一個具有自己樣式的單獨框架中(索引 0 是此頁面的 CSS)。
然後,我們遍歷為即時示例定義的規則,並匹配任何型別為 CSSPageRule 的規則,因為這些規則對應於 @page 規則。對於匹配的物件,我們記錄 style 及其所有值。
if (typeof window.CSSPageDescriptors === "undefined") {
log("CSSPageDescriptors is not supported on this browser.");
} else {
// Get stylesheets for example and then get its cssRules
const myRules = document.getElementById("css-output").sheet.cssRules;
for (const rule of myRules) {
if (rule instanceof CSSPageRule) {
log(`${rule.style}`);
log(`margin: ${rule.style.margin}`);
// Access properties using CamelCase syntax
log(`marginTop: ${rule.style.marginTop}`);
log(`marginRight: ${rule.style.marginRight}`);
log(`marginBottom: ${rule.style.marginBottom}`);
log(`marginLeft: ${rule.style.marginLeft}`);
log(`pageOrientation: ${rule.style.pageOrientation}`);
// Access properties using snake-case syntax
log(`margin-top: ${rule.style["margin-top"]}`);
log(`margin-right: ${rule.style["margin-right"]}`);
log(`margin-left: ${rule.style["margin-left"]}`);
log(`margin-bottom: ${rule.style["margin-bottom"]}`);
log(`page-orientation: ${rule.style["page-orientation"]}`);
log(`size: ${rule.style.size}`);
// Log the original CSS text using inherited property: cssText
log(`cssText: ${rule.style.cssText}`);
log("\n");
}
}
}
結果
結果如下。請注意,日誌頂部顯示的 style 物件應該是 CSSPageDescriptors 以匹配當前規範,但在某些瀏覽器中可能是 CSSStyleDeclaration。另請注意,駝峰式和下劃線式屬性的相應值與 @page 宣告相匹配,並且 page-orientation 為空字串 "",因為它未在 @page 中定義。
規範
| 規範 |
|---|
| CSS 物件模型 (CSSOM) # csspagedescriptors |
瀏覽器相容性
載入中…