element()

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

element() CSS 函数定义了一个从任意 HTML 元素生成的 <image> 值。这个图像是实时的,这意味着如果 HTML 元素发生变化,使用结果值的 CSS 属性会自动更新。

一个特别有用的场景是,在 HTML <canvas> 元素中渲染图像,然后将其用作背景。

在 Gecko 浏览器上,你可以使用非标准的 document.mozSetImageElement() 方法来更改用作给定 CSS 背景元素背景的元素。

语法

css
element(id)

其中

id

要用作背景的元素 ID,使用 HTML 属性 #id 在元素上指定。

正式语法

<element()> = 
element( <id-selector> )

<id-selector> =
<hash-token>

示例

这些示例在支持 -moz-element() 的 Firefox 构建版本中有效。

一个比较现实的例子

此示例使用一个隐藏的 <div> 作为背景。背景元素使用渐变,但还包含作为背景一部分渲染的文本。

html
<div id="target-box">
  <p>This box uses the element with the #my-background ID as its background!</p>
</div>

<div id="background-container">
  <div id="my-background">
    <p>This text is part of the background. Cool, huh?</p>
  </div>
</div>
css
#target-box {
  width: 400px;
  height: 400px;
  background: -moz-element(#my-background) no-repeat;
}

#background-container {
  overflow: hidden;
  height: 0;
}

#my-background {
  width: 1024px;
  height: 1024px;
  background-image: linear-gradient(to right, red, orange, yellow, white);
}

#my-background p {
  transform-origin: 0 0;
  rotate: 45deg;
  color: white;
}

ID 为“my-background”的 <div> 元素被用作内容的背景,内容包括段落“此框使用 ID 为 #my-background 的元素作为其背景!”。

页面预览

这个基于 Vincent De Oliveira 的示例<div id="css-result"> 中创建了 <div id="css-source"> 的预览。

HTML

html
<div id="css-source">
  <h1>Page Preview</h1>
</div>
<div id="css-result"></div>

CSS

css
#css-result {
  background: -moz-element(#css-source) no-repeat;
  width: 256px;
  height: 32px;
  background-size: 80%;
  border: dashed;
}

结果

规范

规范
CSS 图像模块第 4 级
# element-notation

浏览器兼容性

另见