HTML DOM Style top 属性

htmldomweb developmentfront end technology更新于 2024/5/23 18:52:17

HTML DOM Style top 属性返回并修改 HTML 文档中已定位 HTML 元素的顶部位置。

语法

以下是语法 −

1. 返回 top

object.top

2. 修改 top

object.top = “value”

此处,value 可以为 −

Sr.NoValue &
1initial
设置此属性值为默认值。
2inherit
从其父元素继承此属性值。
3percentage(%)
以父元素宽度的百分比定义值。
4length
以长度单位定义 top 值。
5auto
让浏览器设置 top 的值位置。

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

示例

<!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;
      position: relative;
   }
   .show {
      font-size: 1.2rem;
      margin: 1rem 0;
   }
</style>
<body>
<h1>DOM Style top Property Demo</h1>
<div class='square'></div>
<button onclick="set()" class="btn">Set top position</button>
<script>
   function set() {
      document.querySelector('.square').style.top = "200px";
   }
</script>
</body>
</html>

输出

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


相关文章


有用资源