Style background 属性

定义和用法

background 属性以简写形式设置或返回最多八个单独的背景属性。

通过此属性,您可以设置/返回以下一项或多项(以任意顺序):

DOM 属性 CSS 属性
backgroundAttachment background-attachment
backgroundClip background-clip
backgroundColor background-color
backgroundImage background-image
backgroundOrigin background-origin
backgroundPosition background-position
backgroundRepeat background-repeat
backgroundSize background-size

Ang mga ito na attribute ay maaari ring gamitin sa mga hiwalay na style property para sa mas mabuting kontrol. Inaanyayahan ang mga hindi napapahalagang mga tagapaglathala na gumamit ng mga hiwalay na attribute.

Bilang karagdagan:

CSS Tutorial:CSS Background

CSS3 Tutorial:CSS3 Background

CSS Reference Manual:Background property

Halimbawa

I-set ang estilo ng background ng dokumento:

document.body.style.background = "#f3f3f3 url('img_tree.png') no-repeat right top";

亲自试一试

May higit pang mga TIY na halimbawa sa ibaba ng pahina.

Pagsusulit

I-halimbawa ang background property:

object.style.background

I-set ang background property:

object.style.background = "color image repeat attachment position size origin clip|initial|inherit"

Halimbawa ng value ng attribute

Halimbawa ng value Paglalarawan
color I-set ang kulay ng background ng elemento.
image I-set ang image na background ng elemento.
repeat I-set ang paraan ng pagpalit ng image na background.
attachment I-set kung ang image na background ay nakasadsad o sumasailalim sa paggalaw ng pahina.
position I-set ang pagsisimula ng laki ng image na background.
size I-set ang laki ng image na background.
origin I-set ang lugar ng lokasyon ng background.
clip I-set ang lugar ng pagpipinta ng image na background.
initial I-set ang attribute na ito sa kanyang default na halimbawa. Tingnan ang initial.
inherit Mumunuan ang attribute na ito mula sa magulang na elemento. Tingnan ang inherit.

Detalye ng teknolohiya

Default na halimbawa: transparent none repeat scroll 0% 0% auto padding-box border-box
Halimbawa ng output: String na naglalarawan ng background ng elemento.
Versyon ng CSS: CSS1 + mga bagong property sa CSS3

Higit pang mga halimbawa

Halimbawa 2

Ibang div na nagbabago ng background:

document.getElementById("myDIV").style.background = "url('smiley.gif') blue repeat-x center";

亲自试一试

例子 3

为文档设置背景颜色:

document.body.style.backgroundColor = "red";

亲自试一试

例子 4

为文档设置背景图像:

document.body.style.backgroundImage = "url('img_tree.png')";

亲自试一试

例子 5

将背景图像设置为不重复:

document.body.style.backgroundRepeat = "repeat-y";

亲自试一试

例子 6

将背景图像设置为固定(不会滚动):

document.body.style.backgroundAttachment = "fixed";

亲自试一试

例子 7

更改背景图像的位置:

document.body.style.backgroundPosition = "top right";

亲自试一试

例子 8

返回文档的背景属性值:

document.body.style.background;

亲自试一试

浏览器支持

background 是 CSS1 (1996) 特性。

所有浏览器都完全支持它:

Chrome Edge Firefox Safari Opera IE
Chrome Edge Firefox Safari Opera IE
支持 支持 支持 支持 支持 支持

注释

CSS3 (1999) 中添加了三个新属性: