首页 > 解决方案 > 使位置固定不可滚动

问题描述

我想知道是否有办法使位置固定不动的 div ,所以如果用户滚动 div 将不动到初始位置。我需要它,因为我在另一个 div 中生成了一个 toast,并且我需要在前景中使用这个 toast,否则它将在 div 内部生成(带有滚动条并且部分可见)。

这是一个示例图像,可以更好地解释:

使用绝对位置: 在此处输入图像描述

位置固定(预期效果): 在此处输入图像描述

这是我的组件代码(它是一个子组件):

        <div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="position:absolute; z-index:999; left:80%; width:300px;opacity:1;cursor:unset !important" *ngIf="!isCollapsed && onlyOnePopup == dataItem.Id">
          <div class="toast-header" style="background-color: #00549F;">
            <strong class="mr-auto" style="color:#fff;"></strong>
            <button (click)="onlyOnePopup = null && isCollapsed = true" type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
              <span aria-hidden="true" class="close" style="color:white;">&times;</span>
            </button>
          </div>
          <div class="toast-body" style="font-family:Font; white-space:pre-line; color:black; cursor:unset">
            TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
          </div>
        </div>

标签: htmlcssangularfrontendclient

解决方案


使用position: fixed,然后设置所需的确切位置。这是一个片段,向您展示了如何执行此操作的示例。

body {
  height: 2000px;
  background-color: aqua;
}

.fixed-div {
  width: 200px;
  heigth: 200px;
  background-color: white;
  padding: 50px;
  
  position: fixed;
  top: 0px;
  right: 0px;
  margin-right: 20px;
  margin-top: 20px;
}
<html>
<head></head>
<body>
  <div class="fixed-div">
     Fixed Div
  </div>
</body>
</html>


推荐阅读