HTML DOM Style position 屬性
定義和用法
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 属性的值从父元素继承。 |
瀏覽器支持
所有主要瀏覽器都支持position 屬性。
注意: IE7及更早的版本不支持"inherit"值。IE8 只有規定了!DOCTYPE 才支持"inherit"。 IE9 支持"inherit"。
實例
實例
把元素的position(位置)從static(靜態,默認)改為absolute(絕對):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.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>
<p>这是一个段落。</p>
<p>这是一个段落。</p>
<p>这是一个段落。</p>
<input type="button" id="b1" onclick="displayResult()" value="定位我">
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.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>
<p>这是一个段落。</p>
<p>这是一个段落。</p>
<p>这是一个段落。</p>
<input type="button" id="b1" onclick="displayResult()" value="定位我">
</body>
</html>
嘗試一下»
Style對象