HTML DOM Style position 属性

htmldomweb developmentfront end technology更新于 2024/5/23 19:56:17

HTML DOM Style 的position属性用于返回并修改HTML元素在HTML文档中使用的定位方法。

语法

以下是语法 −

1. 返回position

object.position

2. 修改position

object.position = “value”

此处,value可以为 −

Sr.NoValue &
1initial
将此属性值设置为其默认值。
2inherit
它从其父元素继承此属性值。
3static
在这种情况下,元素将按照它们在文档流中出现的顺序进行渲染。
4absolute
在这种情况下,元素将相对于文档中第一个定位的祖先元素进行定位。
5fixed
在这样,元素将相对于文档中的浏览器窗口进行定位。
6relative
在这种情况下,元素将相对于其在文档中的正常位置进行定位。
7sticky
在这种情况下,元素将根据用户在文档中的滚动位置进行定位。

让我们看一个 HTML DOM Style position 属性的示例 −

示例

<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 40%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem 0;
   }
   .square {
      width: 100px;
      height: 100px;
      background: #db133a6b;
      top: 150px;
      left: 50%;
   }
   .show {
      font-size: 1.2rem;
      margin: 1rem 0;
   }
</style>
<body>
<h1>DOM Style position Property Demo</h1>
<div class='square'></div>
<button onclick="set()" class="btn">Set Position</button>
<script>
   function set() {
      document.querySelector('.square').style.position = "fixed";
   }
</script>
</body>
</html>

输出

点击“设置位置”按钮设置粉色方块的位置。


相关文章


有用资源