HTMLElement: anchorElement 属性
非标准:此特性未标准化。我们不建议在生产环境中使用非标准特性,因为它们浏览器支持有限,并且可能会更改或被移除。但是,在没有标准选项的特定情况下,它们可以是合适的替代方案。
HTMLElement 接口的 anchorElement 属性返回对元素锚定元素的引用。这仅在元素通过 anchor HTML 属性与锚定点相关联的情况下才有效,而不是通过 CSS 的 anchor-name 和 position-anchor 属性与锚定点相关联的元素。
值
一个表示元素锚定元素的 HTMLElement 实例,如果它没有锚定元素,则返回 null。
示例
基本用法
本示例在 HTML 中将一个元素与一个锚定点关联起来,并使用 JavaScript 来检索对锚定元素的引用。
HTML
在 HTML 中,我们创建一个 <div> 元素,其 id 为 example-anchor。这将是我们的锚定元素。然后,我们包含另一个具有 infobox 类和设置为 example-anchor 的 anchor 属性的 <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 属性的讨论。
浏览器兼容性
加载中…
另见
- HTML
anchor属性 - CSS
anchor-name和position-anchor属性 - CSS anchor positioning 模块