HTMLElement: anchorElement 屬性

非標準:此特性未標準化。我們不建議在生產環境中使用非標準特性,因為它們瀏覽器支援有限,並且可能會更改或被移除。但是,在沒有標準選項的特定情況下,它們可以是合適的替代方案。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

HTMLElement 介面的 anchorElement 屬性返回對元素錨定元素的引用。這僅在元素透過 anchor HTML 屬性與錨定點相關聯的情況下才有效,而不是透過 CSS 的 anchor-nameposition-anchor 屬性與錨定點相關聯的元素。

一個表示元素錨定元素的 HTMLElement 例項,如果它沒有錨定元素,則返回 null

示例

基本用法

本示例在 HTML 中將一個元素與一個錨定點關聯起來,並使用 JavaScript 來檢索對錨定元素的引用。

HTML

在 HTML 中,我們建立一個 <div> 元素,其 idexample-anchor。這將是我們的錨定元素。然後,我們包含另一個具有 infobox 類和設定為 example-anchoranchor 屬性的 <div>。這會將第一個 <div> 指定為第二個 <div> 的錨定點,將兩者關聯起來。

我們還包含一個 <p> 元素用於輸出一些結果。

html
<div class="anchor" id="example-anchor">⚓︎</div>

<div class="infobox" anchor="example-anchor">
  <p>This is an information box.</p>
</div>

<p class="output"></p>

JavaScript

我們使用 JavaScript 獲取定位元素和輸出元素的引用,然後將定位元素的 anchorElement 屬性關聯的 id 值列印到輸出中,以顯示錨定元素是定位元素的 anchorElement

js
const posElem = document.querySelector(".infobox");
const outputElem = document.querySelector(".output");

try {
  outputElem.textContent = `The positioned element's anchor element is the ${posElem.anchorElement.id}.`;
} catch (e) {
  outputElem.textContent = `Your browser doesn't support the anchorElement property.`;
}

結果

結果如下。

規範

此屬性目前不是 HTML 規範的一部分。請閱讀關於在 https://github.com/whatwg/html/pull/9144 新增 anchorElement 屬性的討論。

瀏覽器相容性

另見