天天看點

Style position 屬性

Style 對象

定義和用法

position 屬性設定或傳回用于元素定位方法的類型(static(靜态的)、relative(相對的)、absolute(絕對的)或 fixed(固定的))。

文法

設定 position 屬性:

Object.style.position="static|absolute|fixed|relative|inherit"

傳回 position 屬性:

Object.style.position

描述
static 預設。位置設定為 static 的元素,它始終會處于頁面流給予的位置(static 元素會忽略任何 top、bottom、left 或 right 聲明)。
absolute 位置設定為 absolute 的元素,可定位于相對于第一個已定位(非靜态的)的包含它的元素的指定坐标。此元素的位置可通過 "left"、"top"、"right" 以及 "bottom" 屬性來規定。
fixed 位置被設定為 fixed 的元素,可定位于相對于浏覽器視窗的指定坐标。此元素的位置可通過 "left"、"top"、"right" 以及 "bottom" 屬性來規定。不論視窗滾動與否,元素都會留在那個位置。工作于 IE7(strict 模式)。
relative 位置被設定為 relative 的元素,可将其定位于相對于其正常位置的地方,是以 "left:20" 會将元素移至元素正常位置左邊 20 個像素的位置。
inherit position 屬性的值從父元素繼承。

浏覽器支援

Style position 屬性
Style position 屬性
Style position 屬性
Style position 屬性
Style position 屬性

所有主要浏覽器都支援 position 屬性。

注意:

IE7 及更早的版本不支援 "inherit" 值。IE8 隻有規定了 !DOCTYPE 才支援 "inherit"。IE9 支援 "inherit"。

執行個體

把元素的 position(位置)從 static(靜态,預設)改為 absolute(絕對):

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>菜鳥教程(runoob.com)</title>

<script>

function displayResult(){

    document.getElementById("b1").style.position="absolute";

    document.getElementById("b1").style.top="100px";

    document.getElementById("b1").style.left="100px";

}

</script>

</head>

<body>

<p>這是一個段落。</p>

<input type="button" id="b1" onclick="displayResult()" value="定位我">

</body>

</html>

Style 對象