Latest web development tutorials

HTML DOM Style backgroundPosition 屬性

Style 對象參考手冊 Style對象

定義和用法

backgroundPosition 屬性設置或返回元素的背景圖像的位置。

語法

設置backgroundPosition 屬性:

Object.style.backgroundPosition="position"

返回backgroundPosition 屬性:

Object.style.backgroundPosition

提示: backgroundPosition屬性的默認值是:0% 0%。

描述
top left
top center
top right
center left
center center
center right
bottom left
bottom center
bottom right
如果仅指定一个关键字,其他值将是 "center"。
x% y% x 值表示水平位置,y 值表示垂直位置。左上角是 0% 0%。右下角是 100% 100%。如果仅指定一个值,其他值将是 50%。
xpos ypos x 值表示水平位置,y 值表示垂直位置。左上角是 0 0。单位可以是像素(0px 0px)或任何其他的 CSS 单位。如果仅指定一个值,其他值将是 50%。您可以混合使用 % 和单位。
inherit 背景位置属性的设置从父元素继承。


瀏覽器支持

Internet ExplorerFirefoxOperaGoogle ChromeSafari

所有主要瀏覽器都支持backgroundPosition 屬性。

注意: IE7及更早的版本不支持"inherit"值。IE8 只有規定了!DOCTYPE 才支持"inherit"。 IE9 支持"inherit"。


實例

實例

更改背景圖像的位置:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
<style>
div{
background-image: url('img_tree.png');
background-repeat: no-repeat;
width: 400px;
height: 400px;
border: 1px solid #000000;
}
</style>
<script>
function displayResult(){
document.getElementById("div1").style.backgroundPosition="center bottom";
}
</script>
</head>
<body>

<button type="button" onclick="displayResult()">修改背景圖像位置</button>
<br>
<div id="div1">
</div>

</body>
</html>

嘗試一下»


Style 對象參考手冊 Style對象